Ahmer Ali Ahsan Ahmer Ali Ahsan - 3 months ago 10
Javascript Question

Why animate's callback function (complete) executed at start?

Duplicate:

Yes it is but a little bit different from this.

I'm using jQuery 3.1.0 This is my code:

$(document).ready(function () {
ToggleAsideBar();
});

function ToggleAsideBar(){
$(".ah-sidebar-toggle").click(function(){
let toggleSize = $(".ah-logo").width() == 230 ? "50px" : "230px";
$(".ah-logo").animate(
{ width: toggleSize },200,"linear",function () {alert("Animation Complete!");'}
);
});
}


Problem:

In my case, alert show before the animation starts. I want to show alert after the animation completed. Any thoughts what I am doing wrong in above code?

Live Example:

jsfiddle

Answer

You had a collision between jquery's animation and css's transition.
If you decide to use animate - you should remove the transition lines from your css file.

Here is a working version (without the transition in your css):

$(document).ready(function () {
  ToggleAsideBar();
});
function ToggleAsideBar(){
  //Get width of browser
  $(".ah-logo").click(function(){
        let toggleSize = $(".ah-logo").width() == 230 ? "50px" : "230px";
        $(".ah-logo").animate(
          { width: toggleSize },200,"swing"
        ).promise().done(function(){
            alert("Animation Complete!");
          });
  });
  
}
.ah-logo {
  width: 230px;
    
    float: left;
    font-weight: 600;
    font-size: 16px;
    text-align: center;
    overflow: hidden;
    
}

a {
  line-height: 50px;
  display: block;
}
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<div class="ah-logo">
<a href="#">Admin</a>
</div>

Comments