Linking an eventlistener to multiple buttons

Hello everyone, i’ll get right to the point.
I am trying to make a webpage where if you click on one of the buttons, a sound will play. So far I have this code

let buttons = document.querySelector('.popupbutton')
let woodsound = 'zapsplat_foley_wood_squeak_creak_001.mp3'

buttons.addEventListener("click", function(){
  alert('hi')
})

the alert is just to test it.
However it only works on the first button, and I don’t know why.
Here is the HTML

<div class="buttons container-fluid"> 
    <button type="button" id="button1" class="popupbutton btn btn-info navbutton">Info</button>
    <div class="d-none popup"> Hi 1 </div> 
  
    <button type="button" id="button2" class="popupbutton btn btn-info navbutton">Info</button>
    <div class="d-none popup"> Hi 2 </div> 
      
    <button type="button" id="button3" class="popupbutton btn btn-info navbutton">Info</button>
    <div class="d-none popup"> Hi 3 </div> 
      
    <button type="button" id="button4" class="popupbutton btn btn-info navbutton">Info</button>
    <div class="d-none popup"> Hi 4 </div> 
  </div>  
  </div> 

Could someone advise me on how to make all the buttons respond to this event listener?
thank you.

1 Like

querySelector will only target the 1st element it finds:

What if you made the EventListener a basic function and gave each <button> an onclick attribute to call it?

I thought of QuerySelectorAll, and when I tried it, it didn’t work at all.
Is the syntax for that the same as the singular one?

Try forEach() loop that will add listener to every button in buttons

2 Likes

Yes, it is the same syntax i.e:

let buttons = document.querySelectorAll('.popupbutton')

But you get an “Array” (NodeList) so:

buttons[0].addEventListener("click", function(){
  alert('hi')
})

Would work for 1st button

1 Like

So I don’t have a bunch of experience using that array method (you could probably tell)
How exactly would this be structured properly?

buttons.forEach(addEventlistener('click', (alert('hi'))))
let buttons = document.querySelectorAll('.popupbutton')
buttons.forEach((btn) => {
  btn.addEventListener("click", (event) => {
    alert(event.target);
  });
});
1 Like

addEventListener() is a method of HTML element, button in your case. How would you run method in this case?

1 Like

I have lots of studying to do. Thank you all for your help.

You can use a normal for loop to iterate through the NodeList. Just use the basic skills you already learned in the Basic JavaScript section.

1 Like