element.classList.addClass is not a function when testing Animate.css

Viewed 4378

I've downloaded the Animate.min.css from the github repo. I can see an initial animation after page load.

<h1 class="animated bounce delay-2s">Example</h1>

but, if I click on a button:

<button onclick = "myclick()">Animate</button>

the javascript function

function myclick() {
  const element =  document.querySelector('.my-modern');
  element.classList.addClass('animated', 'bounceOutLeft');
}

throws an exception

test_animate.html:14 Uncaught TypeError: element.classList.addClass is not a function
    at myclick (test_animate.html:14)
    at HTMLButtonElement.onclick (test_animate.html:9)

I've also tried adding jquery with no success

<script src="jquery-3.4.1.min.js"></script>

but I've no idea what I'm supposed to do to fix this issue.

I'd expect to see the following paragraph being animated.

<p name="par_test" class="my-modern">Test this</p>

Edit (found that the issue is IE11 specific)

I copied the addClass from debugging the Animate homepage after seeing this line

  function testAnim(x) {
    $('#animationSandbox').removeClass().addClass(x + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
      $(this).removeClass();
    });
  };

As per this comment I've corrected it into

element.classList.add('animated', 'bounceOutLeft');

and now the exception has disappeared, but I still can't see the expected animation only on IE11. In Chrome it is all ok. I've posted this as an issue on github.

2 Answers

Element.classList.addClass is not a function, as you've discovered already. Element.classList.add is, and while IE11 supports it, it does not support supplying multiple arguments to it as you're doing.

There is a polyfill available on MDN which you could use, or you could use jQuery.

After some experiments, I've found that the following code is working for both Chrome and IE11 as expected.

<html>
<head>
  <link rel="stylesheet" href="animate.min.css">
  <script src="jquery-3.4.1.min.js"></script>
</head>
<body>
  <h1 class="animated bounce delay-2s">Example</h1>
  <h2 name="par_test" id ="par_id" class="my-modern">Test this</h2>
  <button onclick = "myclick()">Animate</button>
</body>
<script>
function myclick() {
  $('.my-modern').addClass('bounceOutLeft animated');
}
</script>
</html>

It looks like using the jQuery API addClass (instead of the vanilla JavaScript classList.add) solved my issue.

Actually I derived it from reverse engineering the homepage and not by following the readme of the repository.

Edit

As already pointed out in this answer, the root cause of the issue for IE11 is that

it does not support supplying multiple arguments to Element.classList.add

so, besides adding the polyfill or using jQuery, one could have simply done:

element.classList.add('bounceInDown');
element.classList.add('animated');
Related