0

I have read this is the correct way to get scroll to and animation working in Jquery with the body and html tags. However, this also fires the callback multiple times event if $("body, html") shows only two items in a list. At the most I would think 2, after each iteration it can go up which I'm not sure why, but I need to execute the callback one time with his setup? Any fix?

 $("body, html").animate({ scrollTop: top }, function () {
     animateScroll($topItem);
 });
Huangism
  • 16,278
  • 7
  • 48
  • 74
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

3 Answers3

1

With $("body, html") you're selecting two elements to animate, first body and second html. That's because two callbacks are fired, just like it should be.

See explanation here: Callback of .animate() gets called twice jquery

Try to change your code as follows:

$("html body").animate({ scrollTop: top }, function () {
    animateScroll($topItem);
});
Community
  • 1
  • 1
ihkawiss
  • 986
  • 3
  • 9
  • 25
  • Why does the callback get fired more then two times? – Mike Flynn Aug 11 '14 at 19:51
  • Well, that's not that simple to answer. This snippet http://jsfiddle.net/ihkawiss/40dgsdwf/ shows how animate callback gets fired. Could you provide more code or a snippet to reproduce your issue? Have you already tried my solution, didn't it solve your problem ? – ihkawiss Aug 11 '14 at 19:58
0

you can try this workaround:

var callbackFired=false;
$("body, html").animate({ scrollTop: top }, function () {
    if(!callbackFired){
        animateScroll($topItem);
        callbackFired=true;
    }
});
Amin Jafari
  • 7,157
  • 2
  • 18
  • 43
0

This did it for me.

$("body, html").animate({ scrollTop: top }).promise().done(function() {
                            animateScroll($topItem);
                        });
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341