1

Within my current jQuery code, I wanted to make possible to animate to the top of my webpage and dropdown a hidden element right afterwards. The problem is that I am using an if statement to check wether this element is hidden, but my code runs twice through that if statement, causing the dropdown to slide up immediately after sliding down.

When I run the following code:

$("a#drop-user-box").click(function()
{
    $("html, body").animate({scrollTop: 0}, "slow", function()
    {
        alert("foo");
    });
    return false;
});

It will pop an alert and when I click e.g. the "Ok" button, another alert pops open (meaning the code runs twice). Can anyone explain me why this is happening?

When I add the alert like so:

$("a#drop-user-box").click(function()
{
    alert("foo");
    //$("html, body").animate({scrollTop: 0}, "slow", function()
    //{

    //});
    //return false;
});

It will run the code (in this (example) case the alert) once (but not afterwards).

JSFiddle

Barrosy
  • 1,407
  • 2
  • 25
  • 56

2 Answers2

8

It's because you are animating two elements (body and html) and thus there are two animation complete callbacks. Using the promise method works as you would expect.

$("html, body").animate({scrollTop: 0}, "slow")
.promise().then(function() {
    alert("foo");
});

https://jsfiddle.net/719xffa5/3/

Paul Thomas
  • 2,756
  • 2
  • 16
  • 28
  • 2
    `html,body` is used because of browser compatibility.. in some `html` may work but `body` wont. better to use `Promise` here. http://stackoverflow.com/questions/8790752/callback-of-animate-gets-called-twice-jquery – techie_28 Mar 31 '16 at 09:40
2

Yes. The callback function is running multiple times due two elements are passed in the selector.

To solve your problem, you could use when and then method:

$.when($('html,body').animate({scrollTop: 0},'slow'))
  .then(function() {
     alert('foo');
  });

demo

Alternatively, you could use promise method described here:

$('html, body').animate({scrollTop: 0}, 'slow')
.promise().then(function() {
    alert('foo');
});
Community
  • 1
  • 1
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231