Snorlax
Snorlax

Reputation: 4745

jQuery animation Complete fires before event is complete

fiddle: https://jsfiddle.net/jzhang172/mofnf7ua/1/

It may just be lag on my screen, but it seems that Complete fires before my animate finishes. Is there an issue with my code and if so, how can I correct it so I can achieve the desired result?

$(function(){

$(".hey").click(function(){ 
     var height=$(".two").height(); 

     console.log(height);
     if (height >400){
         $(".two").animate({
               height:"0px",
               opacity:0
          },
          {
            duration:1000,
            complete:function(){
            alert('hey');
           }
         });
     }//ifstatement end
     else {
         $(".two").animate({
            height:"500px",
           opacity:1
         });
   }
 });//clickfunction end
});//function end
.hey{
  background:blue;
  height:50px;
  width:50px;
  transition:1s;
   
}
.two{
  background:red;
    height:500px;
  width:500px;
  transition:1s;
}
.no{
    opacity:1;
display:block;
  transition:1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="hey"></div>

<div class="hey two" id="two">fffffffff</div>

Upvotes: 2

Views: 53

Answers (1)

Rino Raj
Rino Raj

Reputation: 6264

The reason for this is the CSS you added transition:1s;. If you remove that it will be working fine.

The animate() method performs a custom animation of a set of CSS properties. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Default speed of the animation value is 400 milliseconds.

If you want to give a spped for animation you can give it via jQuery animate() itself.

Working Demo

$(function() {

  $(".hey").click(function() {
    var height = $(".two").height();

    console.log(height);
    if (height > 400) {
      $(".two").animate({
        height: "0px",
        opacity: 0
      }, {
        duration: 1000,
        complete: function() {
          alert('hey');
        }
      });
    } //ifstatement end
    else {
      $(".two").animate({
        height: "500px",
        opacity: 1


      });
    }
  }); //clickfunction end


}); //function end
.hey {
  background: blue;
  height: 50px;
  width: 50px;
  //transition: 1s;

}
.two {
  background: red;
  height: 500px;
  width: 500px;
  // transition: 1s;

}
.no {
  opacity: 1;
  display: block;
  transition: 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="hey"></div>

<div class="hey two" id="two">fffffffff</div>

Upvotes: 2

Related Questions