Your problem resides in that you have 3 different classes with almost the same purpose and you add the same function as a click handler for all 3 different classes.
The solution would be simple, to add an extra class to all 3 different classes called “jacket” specifically for that sole purpose.
const covers = document.querySelectorAll('.jacket')
for (let cover of covers) {
cover.addEventListener('click', (evt) => {
evt.currentTarget.classList.add('hide')
})
}
Notice the all in querySelectorAll, this is in case you have more than 1 DOM element that you want to select.
How would this be written if it was using a for loop instead of for…of?
I am trying to figure this out.
I have an example here I think that can be used, but would need to be changed.
function hideAllButtons(button) {
const buttons = button.querySelectorAll(".play, .pause, .speaker");
for (let i = 0; i < buttons.length; i += 1) {
hide(buttons[i]);
}
}
I’m trying to add this into the for loop code.
const covers = document.querySelectorAll('.jacket')
for (let cover of covers) {
cover.addEventListener('click', function (evt) {
evt.currentTarget.classList.add('hide')
})
}
function hideAllButtons(button) {
const buttons = button.querySelectorAll(".play, .pause, .speaker");
for (let i = 0; i < buttons.length; i += 1) {
hide(buttons[i]);
}
}
I tried to insert the jacket code in there but wasn’t able to figure it out.
function addCoverListener(cover) {
const covers = cover.querySelectorAll(".jacket");
for (let i = 0; i < covers.length; i += 1) {
cover.addEventListener('click', function (evt)
hide(covers[i]);
}
}
function addCoverListener(cover) {
const covers = cover.querySelectorAll(".jacket");
for (let i = 0; i < covers.length; i += 1) {
covers.addEventListener('click', function (evt)
hide(covers[i]);
}
}
use covers[i] when you need to reference the single element in the array inside the loop
in forEach you use cover to reference the single element because it is the method that passes the single element to the callback, in the for loop you need to access the single element of the array using bracket notation