Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top