1

Here is the plunker

$(document).ready(function(){
  $('#btn-animate').click(function(){
    animate();
  });
  $('#btn-remove').click(function(){
    $('.to-animate').removeClass('animate');
  });

  function animate(){
    $('.to-animate').removeClass('animate');
    $('.to-animate').addClass('animate');
  }
});

Here if I click on "ANIMATE" button it adds an 'animate' class to the div and animates it(changes color). But if you click again it tries to remove the class 'animate' and add it back so that the animation triggers again.

But it is not happening. Strangely if I click the "REMOVE" button to remove the 'animate' class and then with the "ANIMATE" button add the class it animates again.

Can anyone explain why first button is failing to give the required result? And how can I get the animation be triggered every time I click the "ANIMATE" button?

0

4 Answers 4

2

Typically browsers don't repaint the UI until after all javascript has finished running and most browsers are smart enough to figure out that after the second click of the animate button the DOM is the same before and after and so it doesn't do anything.

Easiest solution is to remove the class then set a timeout to add it back after a short delay.

function animate(){
    $('.to-animate').removeClass('animate');
    setTimeout(function(){$('.to-animate').addClass('animate');}, 10);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This aproach solve the problem. Should be accepted as correct answer.
0

Man, from what I see, everything is working normal, I opened the link and there it is also working normal.

What if you check if the class exists instead of remove?

function animate(){
    if(!$('.to-animate').hasClass('animate')){
        $('.to-animate').addClass('animate');
    }
}

Comments

0

Instead of getting the animation from a class, just do the animation with jquery

$(document).ready(function(){
  $('#btn-animate').click(function(){
    $(this).animate(
    "opacity":"0",
    // whatever animation you want in here
    }, 300);
});

Comments

0

jQuery already has the class for your need. It is called toggleClass

$(document).ready(function() {
  $('#btn-animate,#btn-remove').click(function() {
    $('.to-animate').toggleClass('animate');
});

1 Comment

I don't think toggleClass will be apropriate here. What if he want immediate restart of the animation when clicking on #btn-animate ? Also #btn-remove will now start animation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.