Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add and remove same css class instantly

Tags:

html

jquery

css

I have simple html with div and button. Also i have a css class with CSS3 Transition:

.animate
{
    -webkit-animation-name: animation;
    -webkit-animation-duration: 0.3s;
    -webkit-animation-iteration-count: 2;   
}

I want to start animation by clicking a button. So, i wrote a script, which instantly remove and add again .animate class to div, but unfortunately, it doesn't work. Check it out:

("#button").click(function(){ 
    startAnimation(); 
    });

    function startAnimation()
    {
        if ($("#test-div").hasClass('animate')==true)
        {
            $("#test-div").removeClass('animate');  
            startAnimation();
        }
        else
        {
            $("#test-div").addClass('animate'); 
        }   
    }

Why jquery can't remove and instantly add same class? How can i fix that?

And maybe, there is another way to start css3 transition by clicking any selector?

Thanks.

UPD. I upload script at jsfiddle.net/PfzZN/1/

like image 881
nukl Avatar asked Sep 15 '25 06:09

nukl


1 Answers

If the script that makes the change to DOM is in the same thread, for some reason the change will not apply until the thread is finished. So going by your way, the browser will see as if nothing has happened because the 'animate' class is removed and added in the same thread.

As a workaround, will this be good enough?

function startAnimation()
{  
    $("#flash-message").removeClass('animate');  
    setTimeout(function(){
      $("#flash-message").addClass('animate')
    },1);  
}
like image 198
syockit Avatar answered Sep 17 '25 00:09

syockit