0

I have a function which essentially looks like this:

function scroll(scrollTop) {
  $("body,html").animate({scrollTop: scrollTop});
}

And in Backbone routes, I'm trying to use this function to scroll to a position on a page, again, simplified:

var Router = Backbone.Router.extend({
  routes: {
    "": "index",
    "foo": "foo"
  },

  index: function () {
    scroll(0);
  },

  foo: function () {
    scroll($("#foo").offset().top);
  }
});

This works fine on page load (if loading "/foo"), calling the function manually, or utilizing pushState (as opposed to the hash fragment) routes.

But using hash fragment routes, the animation fails. The scroll position still changes, but instantly, without animation.

Is there a workaround for this?

numbers1311407
  • 33,686
  • 9
  • 90
  • 92
  • Any chance your routes correspond to the id of elements on your page? – Loamhoof Apr 18 '13 at 07:47
  • @Loamhoof yes, apart from the `index` route which scrolls to 0, the others are actually finding an element by id and scrolling to its `offset().top` (I edited the code in question to reflect this). But simply scrolling to 0 has the same problem. – numbers1311407 Apr 18 '13 at 14:15

1 Answers1

2

What you're describing is in fact the browser's behavior when changing the hashtag. That is, navigating from domain.com to domain.com#someId is like asking the browser to "focus" on the element of the page which id is someId. So the window will move to this element. Unfortunately, I don't know any fix to this.

You may want to look at this discussion I found while searching for a possible solution: Modifying document.location.hash without page scrolling.

Community
  • 1
  • 1
Loamhoof
  • 8,293
  • 27
  • 30
  • Yep, that's it, and it's obvious really now that you've pointed it out. Somehow I've been using Backbone for years and never run into this. I guess my dom IDs and routes have just coincidentally never matched. – numbers1311407 Apr 18 '13 at 16:24