0

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...

1 Answers1

2

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.

bransonl
  • 556
  • 3
  • 9
  • I am not using hash anchors, i'm using id's on divs. That's not the problem, if I call animate on document ready it scrolls smoothly to desired div without any problems. But when I wrap it in haschange event function, the animation speed breaks. – Saulius Kriauza Aug 28 '15 at 19:12
  • 1
    That's what id's on divs do, they add anchors. Say your URL is `example.com/#about`. If you have an element with the id `about`, it will automatically jump there. Suppose you start in `example.com` and you change your URL to `example.com/#about`. It'll automatically jump to whatever element has the id `about` if it exists and fires the `hashchange` event. However, since it's already there, the animation does not animate anything. – bransonl Aug 28 '15 at 19:15
  • It's working, can't believe how i didn't think of it... Thank you – Saulius Kriauza Aug 28 '15 at 19:25