Search code examples
jquerytwitter-bootstrapwindow.locationhtml5-historyscrollspy

Updating address bar window.location hash with scrollspy


I've got a menu with scrollspy (using twitter boostrap). I want update the window.location.hash when the user scrolls down to a next section.

The following code works when the user scrolls down:

$(window).on('activate.bs.scrollspy', function (e) {
  location.hash = $("a[href^='#']", e.target).attr("href") || location.hash;
});

However it does not work very well when the user scrolls upwards.

The reason for this is that setting a new location.hash triggers the browser to navigate towards that respective anchor. That triggers a chain reaction in which the user will instantly end up at the top of the page.

Demo in js-fiddle

Now what would be the simplest way to solve that problem?


Solution

  • It is possible to change the state of the URL with HTML5 history, without triggering the browser to follow the new state. This is not supported by all browsers.

    Using history.replaceState() has the additional benefit that when the user uses the back button of the browser it will not just scroll up first.

    $(window).on('activate.bs.scrollspy', function (e) {
        history.replaceState({}, "", $("a[href^='#']", e.target).attr("href"));
    });
    

    See working js-fiddle.