Skip to content
Advertisement

How to change the style of HTML list items using setInterval in JavaScript?

I have a HTML code with 3 list items and the ids for my ul is ‘exercise6-list’

<ul id="exercise6-list">

<li>List 1</li>

<li>List 2</li>

<li>List 3</li>

</ul>

I need to make each li glow for three seconds and repeat itself

So far I have written:

var moveGlow = function() {

 var element = document.querySelector("#exercise6-list");

 // ... to make it glow i've so far used .setAttribute("class", "glow")

};

clearInterval(window.interval);
window.interval = setInterval(moveGlow, 3000);

*I’m very new to programming, but thank you for your help

Advertisement

Answer

To make a timed function we use setInterval, and add the class “glow” to the current element, and remove that class from the previous one.
To cycle through the elements, we use an index-variable, which increases per cycle and loops back around when necessary.

let index = 0;
let elements = document.querySelector("#exercise6-list").children;
let glowFunc = () => {
  if (elements.length <= 0) { // Actually not needed since we know there are 3 elements
    index = 0;
    return;
  }
  index %= elements.length; // Map index to valid values
  elements[(elements.length + index - 1) % elements.length].classList.remove("glow"); // Remove "glow" from previous element
  elements[index].classList.add("glow"); // Add "glow" to current element
  ++index; // Increase 'index'
};

glowFunc(); // Initial call to "start" it without initial delay
setInterval(glowFunc, 3000); // Make it a timed function
li {transition: background-color 0.2s}
.glow {background-color: orange}
<ul id="exercise6-list">
  <li>List 1</li>
  <li>List 2</li>
  <li>List 3</li>
</ul>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement