← til

Resetting scroll in Ember

March 11, 2017
ember

By default, Ember routes will remember your scroll position which is sometimes counter-intuitive. We can easily reset scroll on our route by adding some logic in the activate hook.

// app/routes/index.js
import Ember from 'ember';

App.IndexRoute = Ember.Route.extend({
  activate: function() {
    this._super(...arguments);
    window.scrollTo(0,0);
  }
});

This is also what's suggested in Ember Guides. Problem with this is that we have to write activate hook on every route if we want to reset scroll by default. We can move this logic to mixin, so we can include it to every route where we want to reset scroll position.

$ ember g mixin reset-scroll
// app/mixins/reset-scroll.js
import Ember from 'ember';

export default Ember.Mixin.create({
  activate(){
    this._super(...arguments);
    window.scrollTo(0, 0);
  },
});

We can now use this mixin on our index route.

// app/routes/index.js
import Ember from 'ember';
import ResetScroll from '../mixins/reset-scroll';

App.IndexRoute = Ember.Route.extend(ResetScroll);

We can now use this mixin in every other route too. We can even go step further if we want to reset scroll on every route change and add an initializer.

$ ember g initializer reset-scroll
// app/initializers/reset-scroll.js

import Ember from 'ember';
import ResetScroll from '../mixins/reset-scroll';

export function initialize(/* application */) {
  Ember.Route.reopen(ResetScroll);
}

export default {
  name: 'reset-scroll',
  initialize
};

This initializer will enable resetting scroll position every time we change the route and we can focus on more important stuff.