Search code examples
javascriptjqueryjquery-animatehashchange

jQuery hashchange event instantly executes animation with no speed


I am having trouble with jQuery and wrapping my animation inside hashchange event. When event is triggered animation happens instantly. I need it to be smooth.

    jQuery( document ).ready(function() {
        jQuery(window).on('hashchange', function() {
                jQuery('body').animate({ scrollTop: jQuery(window.location.hash).offset().top}, 'slow');
        });
    });

Everythings is fine if i don't wrap animation inside a hashchange event...


Solution

  • If you're changing a hash to an anchor that exists, it'll automatically jump to that anchor without waiting for the animation. You can see that this happens by just removing your animation since it still jumps. This can be fixed by using hashes in your URL that don't actually have an element with the corresponding id and changing your selector is scrollTop to accommodate for this.

    For example, you could change the id of an "about" section to be about-section and continue to use #about as the hash. Then instead of scrollTop: jQuery(window.location.hash).offset().top, you'd use scrollTop: jQuery(window.location.hash + "-section").offset().top to avoid the automatic jump to the element.