reach4thelasers
reach4thelasers

Reputation: 26899

Backbone.js - Back button restoring scroll position

I've got a web application written in backbone.js. Say I have a page of search results and the user is scrolled to the bottom of the search results. The user clicks on the last search result, and the page is displayed for that result.

I want to support back button, and when the user clicks "back", the router kicks in and redisplays the search page. Problem is when the search page is re-rendered , its scrolled to the top again.

What is the best way to restore the results to the original position?

Upvotes: 4

Views: 2819

Answers (1)

uadnal
uadnal

Reputation: 11425

Consider tracking the scroll position in the view. Then on a render or let the route change position the page

View = Backbone.View.extend({
   initialize: function () {
      var self = this;
      $( window ).on( 'scroll', function () {
         self.position = this.pageYOffset;
      });

   },
   render: function () {
      // render code
      if ( this.position ) {
        window.scrollBy( 0, this.position );
      }
   }
});

Upvotes: 1

Related Questions