cicb
cicb

Reputation: 94

JQuery call an animation function when first ends

I'm trying to make a step by step animation of a div in JQuery. I call the animation with a click, then the second with double click, then third...

My problem is that they overlay. If I start double clicking the div it starts both first and second animations at once and it goes crazy. So I'm trying to only let it activate the dblclick once the first function stopped.

I tried to make it work with if else and .is selector and it doesn't work.

$(document).ready( function (){
    $(".group").one("click", showInfo);
})

function showInfo(){

    $(this).stop().animate({height: "260px"});

    $(".group").one("dblclick", showMoreInfo);

})

function showMoreInfo(){

    $(this).stop().animate({height: "0px"});

    $(".group").one("click", showInfo);

})

Upvotes: 0

Views: 47

Answers (1)

jeprubio
jeprubio

Reputation: 18002

jQuery animate has a complete callback, you can use it to set the next animation:

function showInfo(){
    $(this).stop().animate({height: "260px"}, function () { 
        $(".group").unbind("click");
        $(".group").on("dblclick", showMoreInfo);
    });
}

function showMoreInfo(){
    $(this).stop().animate({height: "20px"}, function() {
        $(".group").unbind("dblclick");
        $(".group").on("click", showInfo);
    });
}

$(document).ready( function (){
   $(".group").on("click", showInfo);
});
.group {
  height: 20px;
  width: 20px;
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="group"></div>

And unbind the previous event in that callbacks.

Upvotes: 2

Related Questions