Search code examples
jquerycsschaining

jQuery chaining not behaving as expected


My undestanding is jQuery doesn't move to the next function until the running one is complete. However it seems like this isn't working for me. For example:

                    $("#bigmap").animate(
                    {
                    opacity: 0
                    }, 500).css("display", "none");     

I expect this would fade out #bigmap and then set its display to none. However, it seems to be set to none immediately.

I'm new to this so sure it's something obvious.


Solution

  • Your best option here is actually this:

    $('#bigmap').fadeOut(500);
    

    This will fade it out and automatically hide it when done.

    To explain a bit why your original code didn't work as you expected, you need to understand a bit about both jQuery animations and javascript.

    jQuery animations go into an animation queue and are executed over time (using timers). The call to .animate() just starts the animation and then that function returns, long before the animation is completed. The animation does not complete until some time later. Thus, the next chained method is executed as soon as the call to .animate() returns (right after the animation was started).

    The chained methods $(selector).aaa().bbbb().cccc() are executed synchronously by the javascript engine so jQuery doesn't control their timing.

    Fortunately, as other answers have also told you, there is a completion function for the .animate() method so that you can execute some code when the animation completes and you can put your code to hide the object in there.

    $('#bigmap').animate({opacity:0}, 500, function() {
        $(this).hide();
    });
    

    Even better than this is to use the .fadeOut() method which will automatically hide the object when done and then you don't even have to worry about this issue at all because the hiding is built into the jQuery .fadeOut() method:

    $('#bigmap').fadeOut(500);