Using a Bootstrap5 toggle switch (which is basically just a checkbox) to toggle on and off lines in a grid. I have it set up so if the toggle is true then add the class which adds lines for the grid and if it's false then remove class and the lines. When I toggle off the class that holds the style for the line gets removed correctly but when I toggle on then the class doesn't come back and toggle the lines on. I am also using a forEach()
to loop through all the divs.
I have console.log
within and they fire for each toggle so I am not sure what I am missing. Here is the code
JS
let gridToggleSwitch = document.querySelector("#gridToggle")
gridToggleSwitch.addEventListener('change', () => {
let boxList = document.querySelectorAll('.box')
let toggleChoice = gridToggleSwitch.checked
if(toggleChoice == true) {
console.log("LINES")
boxList.forEach((e) => {
console.log(e)
e.classList.add('box')
})
} else if (toggleChoice == false) {
console.log('NO LINES')
boxList.forEach((e) => {
console.log(e)
e.classList.remove('box')
})
} else {
console.log('woops')
}
})
CSS:
.box {
border: 1px solid black;
}
SOLVED:
since the grid can change dynamically I needed to also dynamically add an ID to the divs for the grid and instead of using the forEach() for the classes I looped through the ID and added/removed the border style