I want to loop through a number of div elements by element id and use setTimeout to toggle a class. Let me illustrate:
For example take two squares and a button:
<div id="step1" class="steps"></div>
<div id="step2" class="steps"></div>
<button id="btn1">example one</button>
.steps {
height: 50px;
width: 50px;
border: 1px solid black;
}
Before getting to the issue, let me share an example that works. In this case pressing “btn1” highlights the top square briefly in red, then in blue. Here is the JS:
const step1 = document.getElementById('step1');
const step2 = document.getElementById('step2');
const btn = document.getElementById('btn');
const exampleOneData = [
{color: "blue", delay: "1000"},
{color: "red", delay: "2000"}
]
btn1.addEventListener('click', () => {
workingExampleData.forEach((obj) => {
setTimeout(
() => {
step1.style.backgroundColor = obj.color}, obj.delay);
});
});
It’s basically using forEach() to work through the array and within a timeout adjust the style. This seems to work fine.
Now, where I am struggling is using the array object for element IDs to toggle. What I want to do is use an array of objects to loop through different squares. To do this I added a second button and a CSS class for a different colour:
const btn2 = document.getElementById('btn2');
.red {
background-color: red;
}
And then in Javascript I add a new array of objects. In this array I use object with the first key/value pair representing the HTML element id and the second one the setTimout delay as before:
const exampleTwoData = [
{step: "step1", delay: "1000"},
{step: "step2", delay: "2000"}
];
btn2.addEventListener('click', () => {
exampleTwoData.forEach((obj) => {
setTimeout(
() => {
obj.step.classList.toggle('red')}, obj.delay)
});
});
But the issue is it seems I can’t use the syntax of
`obj.step.classList.toggle('red')`
In the loop obj.step should be first = “step1”, then “step2”.
So question is – if I have an array with an object where I store an HTML element id, how do I then use that as the element value on element.classList.toggle()?
In codepen: https://codepen.io/dearestalexander/pen/vYwBxgp
2