20 3 / 2012

Preserving scroll position across pages

When you want to edit specific record, typical rails behavior would be to go to edit page, make your changes, and after saving the record, automatically redirect to model index page. This usually makes user loose its focus on large index pages (where scrolling happens).

One way to solve this problem would be to store scroll position for given page in users browser, and then just scroll to that position automatically when user returns to page. Here is the javascript module that does just that:

@ScrollProcessor =
  process: ->
    return unless Modernizr.localstorage
    @restore() if location.hash == '#scroll'
    $(window).on 'scroll', => @onscroll()

  onscroll: (event) ->
    localStorage.setItem @key, $(window).scrollTop()

  restore: ->
    $(window).scrollTop localStorage.getItem(@key)

  key: "scroll#{location.pathname}"

The only thing you need to do is to call ScrollProcessor.process on document ready callback and it will automatically store the scroll position in browser’s localStorage. It also jumps to saved position when it is loaded if path has ‘#scroll’ anchor. Please note that I’m using Modernizr to detect whether localstorage is supported by the browser.

Now, wherever you wish to link to specific page (or redirect to it), but preserve last scrolled position, just use something like this:

articles_path(anchor: 'scroll')

Its really simple, but it does job well.