David
David

Reputation: 121

Jquery doing things out of order

I am working on a project that will have a slide out menu, will darken the page when a menu item is clicked, move around some divs, then return the screen to view. I've accomplished this with a full screen, fixed position div using .animate to set opacity to 1, move my divs around with .css, then .animate the full screen div back to opacity 0. While it all seems to work, it doesn't work in order. The code runs all the .css commands first, then runs all the .animate commands.

$("#overlay").animate({"opacity":"1"}, "slow")
$(".main").css({"left":"-100%"})
$(".section").css({"left":"-100%"})
$(".pink").css({"left":"0"})
$("#overlay").animate({"opacity":"0"}, "slow")

Code is in the right order, but the .main div moves off the screen, all .section divs move off the screen, the .pink div moves onto the screen, then the #overlay opacity is set to 1, then #overlay opacity is set 0.

Why do all the .css actions trigger, then the .animate actions? How do I go about making them happen in order?

Upvotes: 2

Views: 103

Answers (2)

Netorica
Netorica

Reputation: 19337

you need to learn how to use callbacks in which callbacks are called when an animation finishes

$("#overlay").animate({"opacity":"1"}, "slow",
 //from here is the callback function that is invoked when animation finishes
function(){ 
      $(".main").css("left":"-100%");
      $(".section").css("left":"-100%");
      $(".pink").css("left":"0");
      $(this).animate({"opacity":"0"}, "slow");
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

.animate() is an asynchronous function, so the statements after .animate() runs before the animation is completed. You can use the complete callback to solve this

$("#overlay").animate({
    "opacity": "1"
}, "slow", function () {
    $(".main").css({
        "left": "-100%"
    })
    $(".section").css({
        "left": "-100%"
    })
    $(".pink").css({
        "left": "0"
    })
    $(this).animate({
        "opacity": "0"
    }, "slow")
})

Upvotes: 5

Related Questions