Emberjs scroll to top when changing view
ember.js
Solution
You should probably try and extend `Ember.Route` and add your `window.scrollTo` in the `enter` callback. Then instead of using Ember's `Route` for your leaf routes, you call your route .`extend()`, so they'll automatically scroll up when you enter a route/state. Something similar to this:
// define your custom route and extend "enter"
var MyRoute = Em.Route.extend({
enter: function(router) {
// for now on, all the routes that extend this,
// will fire the code in this block every time
// the application enters this state
// do whatever you need to do here: scroll and whatnot
}
});
App.Router = Em.Router.extend({
enableLogging: true,
location: 'hash',
index: Em.Route.extend({
route: '/',
connectOutlets: function(router) {
...
},
// on your leaf routes, use your own custom route that
// does your scroll thing or whatever you need to do
home: MyRoute.extend({
route: '/',
connectOutlets: function (router, context) {
...
}
}),
// other routes...
})
});
does it make sense?
Problem
When the main view of my application is switched (new route that reconnects the main outlet of my application controller) I want the page to be scrolled to the top. Otherwise it's a bit strange that I navigate to another page-like view and the viewport is still lost somewhere where I left off. I hacked a solution and wonder if there's a better way or if anyone has the same thing. Here's what I do: ``` App.ApplicationController = Ember.Controller.extend({ connectOutlet: function(){ window.scrollTo(0, 0); this._super.apply(this, arguments); } }); ```