Search code examples
jquerycssjquery-animateaddclassremoveclass

Begin an event after the previous is done


On the next script of an event after click a button I want that the last 2 jquery events begin after the animations before have been done.

How can I do this?

<script>
$(document).ready(function() {
    $("button").click(function(){
        $("img:first").removeClass("bounceIn").addClass("animated lightSpeedOutleft")
        $("img:last").removeClass("bounceIn").addClass("animated lightSpeedOut");
        $("button:first").removeClass("bounceIn").addClass("animated flipOutX");
        $('div:first-child').addClass("display");
        $('div:last-child').removeClass("display").addClass("animated fadeInUp");
    });
});
</script>

Solution

  • If you know the duration of your CSS animations you can use setTimeout to delay your response.

    /// say this lightSpeedOutleft CSS animation takes a second to complete
    $("img:first").removeClass("bounceIn").addClass("animated lightSpeedOutleft")
    /// set your timeout for a second
    setTimeout(function(){
      /// do further things here.
    }, 1000);
    

    However, if you do not know the animations duration — or you wish to be more precise — you can use animation specific events. Be warned though, these events are rather new and wont be fully implemented across all browsers yet, and in some they will require vendor prefixes:

    1. AnimationStart
    2. AnimationIteration
    3. AnimationEnd

    Example usage:

    $("img:first")
      .removeClass("bounceIn")
      /// you can list your vendor prefixed events here, or implement a better 
      /// vendor-prefix detection solution.
      .on('animationend webkitAnimationEnd', function(e){
        if ( e.animationName == 'YOUR CSS animation-name GOES HERE' ) {
          /// do something else here depending on e.animationName
        }
      })
      .addClass("animated lightSpeedOutleft")
    ;
    

    A few places to read about these events:

    All things considered, using setTimeout is perfectly valid, especially for simple animations.