0

I was playing with animate.css and built my own Javascript function to trigger animation events.

This very simple function (triggered through an onClick event on a button) is only three (four) lines long, but it runs into a truly mind-boggling error.

The anim function first removes the class from the element, then adds it, so that multiple presses on the button will keep running the animation. Unfortunately, I found that it didn't work! That is, the animation runs once (the first time only), and then fails to run subsequently.

In a stroke of serendipity, I discovered that adding the line console.log(element_name) in line 3 suddenly made it work.

I was very puzzled with this behaviour, and so I experimented with adding other console.log lines but strangely only the line console.log(element_name) works!

To ensure that it wasn't a quirk in the development environment, I reproduced it in JSFiddle here.

function anim(element_name){ //'animate' is a reserved keyword
    removeClass(element_name, 'bounceInDown');
    console.log(element_name); //Very cute behaviour!!! when I put this line here, it works, if i don't it doesnt.
    //console.log('a'); //Not all console.logs work
    addClass(element_name, 'bounceInDown');
}

function addClass(element, classname){
    element.classList.add(classname);
}

function removeClass(element, classname){
    element.classList.remove(classname);
}
Lieu Zheng Hong
  • 676
  • 1
  • 10
  • 22

1 Answers1

1

That is because the javascript compilers try to do several actions at a time, so your class never gets deleted! The solution for this is to make a reflow of the page and you can do it for example like this:

document.body.clientHeight;

Change the log to that and problem solved!

Vandervals
  • 5,774
  • 6
  • 48
  • 94
  • Thank you for your answer! Your explanation and solution are correct, but can you explain why `console.log(element_name)` works while other `console.log` commands don't? – Lieu Zheng Hong May 14 '15 at 07:51
  • 1
    That is because if your browser has to get an element, it fires a reflow. There are many other things that would (at the beginging I used a 15ms setTimeout) but I think the one I showed you is the best. – Vandervals May 14 '15 at 07:54
  • 1
    @LieuZhengHong: Because logging the `element_name` accesses its properties, and some of them (like `clientLeft` etc) trigger a reflow when being computed (and the DOM notices that class is absent and starts the animation) – Bergi May 14 '15 at 07:56