Skip to content
Advertisement

How to add an event listener to all items in array

so this is noobie .. but i am trying to complete a challenge with more due diligence than just downloading the answer,

my current html code is:

<!DOCTYPE html>
<html lang="en" dir="ltr">

    <head>
      <meta charset="utf-8">
      <title>Drum Kit</title>
      <link rel="stylesheet" href="styles.css">
      <link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
    </head>
    
    <body>
    
      <h1 id="title">Drum 🥁 Kit</h1>
      <div class="set">
        <button class="w drum">w</button>
        <button class="a drum">a</button>
        <button class="s drum">s</button>
        <button class="d drum">d</button>
        <button class="j drum">j</button>
        <button class="k drum">k</button>
        <button class="l drum">l</button>
      </div>
    
    
      <footer>
        Made with ❤️ in London.
      </footer>
      <script src="index.js" charset="utf-8"></script>
    </body>

my javascript codes :

   document.querySelector("button").addEventListener("click", handleClick);
    function handleClick() {
        alert("I got clicked!");
    }
    
    
    document.querySelectorAll(".drum")[1, 2, 3, 4, 5, 6].addEventListener("click", handleClick);

essentially, the current code is running the event listener for the first and last item of the array only, trying to add it to all 6 but am stuck

thanks to all

Advertisement

Answer

Instead of attaching listeners to each button, add one to the container (set) and, using event delegation, let that listener capture all the events that “bubble up” the DOM from its child elements, and call a function.

const set = document.querySelector('.set');
set.addEventListener('click', handleClick, false);

function handleClick(e) {  
  if (e.target.matches('button')) {
    const { textContent } = e.target;
    console.log(`Banging the ${textContent} drum!`);
  }
}
<h1 id="title">Drum 🥁 Kit</h1>
<div class="set">
  <button class="w drum">w</button>
  <button class="a drum">a</button>
  <button class="s drum">s</button>
  <button class="d drum">d</button>
  <button class="j drum">j</button>
  <button class="k drum">k</button>
  <button class="l drum">l</button>
</div>
<footer>
  Made with ❤️ in London.
</footer>

Additional documentation

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement