'sound when clicking a button works for one but not for ALL
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);
}
Solution 1:[1]
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.
Solution 2:[2]
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");
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mubasher Ali |
| Solution 2 | code_monk |
