Search code examples
jquerycssjquery-animatecss-animations

How to re-animate a div in CSS and jQuery


I am working on this demo. Why am I not able to re-animate the animation after one click? The CSS rules and jQuery works only for first-time click.

<div class="animatetop"></div>
<button id="clicker">Click Me</button>

.animatetop {
    height:250px;
    width:250px;
    background-color:#FFCC33
}
.animated {
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
}
@-webkit-keyframes fadeInUp {
    0% {
        opacity: 0;
        -webkit-transform: translateY(50px);
        transform: translateY(50px);
        animation-delay:2s;
    }
    100% {
        opacity: 1;
        -webkit-transform: translateY(0);
        transform: translateY(0);
        animation-delay:2s;
    }
}
@keyframes fadeInUp {
    0% {
        opacity: 0;
        -webkit-transform: translateY(50px);
        -ms-transform: translateY(50px);
        transform: translateY(50px);
        animation-delay:2s;
    }
    100% {
        opacity: 1;
        -webkit-transform: translateY(0);
        -ms-transform: translateY(0);
        transform: translateY(0);
    }
}
.fadeInUp {
    -webkit-animation-name: fadeInUp;
    animation-name: fadeInUp;
    animation-delay:2s;
}


$(document).ready(function () {
    $("#clicker").on("click", function () {
        // alert( "man nemidanam" );
        $('.animatetop').addClass('animated fadeInUp');
    });
});

Solution

  • You can only add a class to an object once. Once it is there, adding it again does nothing. You'll have to remove the classes animated fadeInUp once the animation completes.

    One way to do this is with setTimeout():

    $(document).ready(function () {
        $("#clicker").on("click", function () {
            // alert( "man nemidanam" );
            $('.animatetop').addClass('animated fadeInUp');
            setTimeout(function(){
    
                $('.animatetop').removeClass('animated fadeInUp');
    
            }, 1500);
        });
    });
    

    JSFiddle