Smooth scroll to internal hash links, revisited

An improved code snippet I’m mostly putting here for my own reference:

$('a[href*=#]').on('click',function(e) { 
  var id = $(this).attr('href').match(/#\w+$/)[0];
  if ($(id).length) { // otherwise, it's a link to a different page
    e.preventDefault();
    var top = $(id).offset().top;
    $('html,body').animate({'scrollTop':top}, 'fast', function() {
      if ("onhashchange" in window) { // test if hashchange is available
        history.pushState(null,null,id);
      } else {
        window.location.hash = id;
      }
    });
  };
});

Leave a Reply

Your email address will not be published. Required fields are marked *

*