Scrolling to top *after* leaving current page, but *before* next page

I’m currently using Iron Router and paging/scrolling feels awkward as the current scrolling position is kept when going to the previous/next page.

There is a workaround that will scroll to the top of the current page before going to the next one. But this is visually very noisy.

onBeforeAction: function(){
	// scroll to top before going to next page
	window.scrollTo(0,0);
}

Is there an approach that would scroll to the top after current page is hidden and before displaying content of the new page? Or is there another solution?

website: http://eboy.io/pool/all/1
GitHub: https://github.com/c6y/eboydb

There’s a package that does this which also handles hashtags and stepping back through history.

Or you could try onRun:

// Scroll to the top of the page on every route transition
// TODO: Doesn't handle back, doesn't handle hashtags
Router.onRun(function() {
  // Only required on client
  if ( Meteor.isClient ) {
    // Wait for template to render
    _.defer(function() {
      // Animate the scroll
      $('body,html').({
        scrollTop: 0,
      }, 200);
    });
  }
  this.next();
}); 

That code will run after the new template has rendered. If timing really matters, you could try onAfterAction but beware problems with these functions, the sequence and frequency is not always what you might expect.

Thanks Oliver! I’m using your code with a small amendment (“animate” was missing) and inside a controller:

onRun: function() {
  // Only required on client
  if ( Meteor.isClient ) {
    // Wait for template to render
    _.defer(function() {
      // Animate the scroll
      $('body,html').animate({
       scrollTop: 0,
      }, 100);
    });
  }
  this.next();
},

Still—this does not scroll to top after the current page content is hidden and before next page’s content is shown … that would be much smoother.

Thanks again!

For the record, the problem was solved when the project was ported from Iron Router to Flow Router. Pages do scroll to the top on next/previous pages. No edits needed.