Can someone show me why if I try to play a sound like so
const button = document.querySelector(".button");
button.addEventListener("click", function () {
document.getElementById("click").play("click.mp3");
});
the sound will only play on the first button (I understand this since it is targeting the first element) with the class .button but if I use querySlectorAll it does not play at all please?
And how can I make it play in all the buttons with the class .button?
Thanks in advance.
Thanks to Barmar for suggesting to use a loop. I did like in below and it works great.
for (let button of buttons) {
button.addEventListener("click", function () {
document.getElementById("click").play("click.mp3");
});
console.log(button);
}
In my case efficient solution will be addEventListener to the parent that contain these buttons and make a check condition that if clicked element has some class or data attribute then make your sound play.
The most elegant way would be to use querySelectorAll, which returns a NodeList, which can be coerced into an array.
const buttons = Array.from(document.querySelectorAll(".button"));
buttons.forEach(button => {
button.addEventListener("click", function () {
document.getElementById("click").play("click.mp3");
});
});