I have a HTML code with 3 list items and the ids for my ul is ‘exercise6-list’
JavaScript
x
10
10
1
<ul id="exercise6-list">
2
3
<li>List 1</li>
4
5
<li>List 2</li>
6
7
<li>List 3</li>
8
9
</ul>
10
I need to make each li glow for three seconds and repeat itself
So far I have written:
JavaScript
1
11
11
1
var moveGlow = function() {
2
3
var element = document.querySelector("#exercise6-list");
4
5
// ... to make it glow i've so far used .setAttribute("class", "glow")
6
7
};
8
9
clearInterval(window.interval);
10
window.interval = setInterval(moveGlow, 3000);
11
*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.
JavaScript
1
15
15
1
let index = 0;
2
let elements = document.querySelector("#exercise6-list").children;
3
let glowFunc = () => {
4
if (elements.length <= 0) { // Actually not needed since we know there are 3 elements
5
index = 0;
6
return;
7
}
8
index %= elements.length; // Map index to valid values
9
elements[(elements.length + index - 1) % elements.length].classList.remove("glow"); // Remove "glow" from previous element
10
elements[index].classList.add("glow"); // Add "glow" to current element
11
++index; // Increase 'index'
12
};
13
14
glowFunc(); // Initial call to "start" it without initial delay
15
setInterval(glowFunc, 3000); // Make it a timed function
JavaScript
1
2
1
li {transition: background-color 0.2s}
2
.glow {background-color: orange}
JavaScript
1
5
1
<ul id="exercise6-list">
2
<li>List 1</li>
3
<li>List 2</li>
4
<li>List 3</li>
5
</ul>