Home > Enterprise >  How do I get one animation to occur after another when Start button is pressed?
How do I get one animation to occur after another when Start button is pressed?

Time:03-30

I have the following functions. I want box 3 to move only after box 1 and box 2 have finished moving. Right now, it's moving right away. I assume I would put all the functions under one .click function but I tried a few times and it still does not work.

$(function() {
  $("button").click(function() {
    $("#box1").animate({
      left: $(window).width() - 800
    }, {
      complete: function() {
        $("#box1").hide();
      }
    });
  });

  $("button").click(function() {
    $("#box2").animate({
      left: $(window).width() - 800
    }, {
      complete: function() { // complete call back
        $("#box2").hide(); // can hide or remove this element
      },
    });
  });

  $("button").click(function() {
    $("#box3").animate({
      right: $(window).width() - 200,
      top: $(window).height() - 200
    });
  });
});
#box1,
#box2,
#box3 {
  width: 30px;
  height: 50px;
  position: absolute;
  text-align: center;
  font-family: Times New Roman;
}

#box1 {
  background-color: skyblue;
  left: 0px;
  top: 50px;
}

#box2 {
  background-color: green;
  left: 0px;
  top: 120px;
}

#box3 {
  background-color: black;
  left: 100px;
  top: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button> Start </button>

<div id="box1">
    <p> BOX 1 </p>
</div>

<div id="box2">
    <p> BOX 2 </p>
</div>

<div id="box3">
    <p> BOX 3 </p>
</div>

CodePudding user response:

If I understand correctly, I simply smashed the first two click handlers together and moved the animation from the third one into the complete callback on #2.

$(function() {
  $("button").click(function() {
    $("#box1").animate({
      left: $(window).width() - 800
    }, {
      complete: function() {
        $("#box1").hide();
      }
    });

    $("#box2").animate({
      left: $(window).width() - 800
    }, {
      complete: function() { // complete call back
        $("#box2").hide(); // can hide or remove this element

        $("#box3").animate({
          right: $(window).width() - 200,
          top: $(window).height() - 200
        });
      }
    });
  });
});
#box1,
#box2,
#box3 {
  width: 30px;
  height: 50px;
  position: absolute;
  text-align: center;
  font-family: Times New Roman;
}

#box1 {
  background-color: skyblue;
  left: 0px;
  top: 50px;
}

#box2 {
  background-color: green;
  left: 0px;
  top: 120px;
}

#box3 {
  background-color: black;
  left: 100px;
  top: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button> Start </button>

<div id="box1">
  <p> BOX 1 </p>
</div>

<div id="box2">
  <p> BOX 2 </p>
</div>

<div id="box3">
  <p> BOX 3 </p>
</div>

  • Related