vendredi 29 septembre 2017

How to add class to random element in pure javascript

I have a ul with some li's inside. I want to randomly select an li and add an .active class for 1second, then remove .active class and randomly select a next li.

I am trying to do this without the use of setInterval or Timeout, so I have tried using requestAnimationFrame although I think my logic with javascript is not quite right on randomizing.

Currently I have it working but it selects the same li each time the function is called again.

<ul>
  <li class="light active"></li>
  <li class="light"></li>
  <li class="light"></li>
  <li class="light"></li>
  <li class="light"></li>
</ul>

Javascript

(function() {

var lights = document.getElementsByClassName("light");
var random = Math.floor(Math.random() * (lights.length - 1)) + 0;
var randomLight = lights[random];

function repeatOften() {
  randomLight.classList += randomLight.classList ? ' active' : ' light';
  requestAnimationFrame(repeatOften);
}
requestAnimationFrame(repeatOften);

})();

Here is a pen: http://ift.tt/2xMgdRo

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire