purelmnz
purelmnz

Reputation: 13

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

Upvotes: 1

Views: 4222

Answers (3)

Yehia Khalil
Yehia Khalil

Reputation: 31

Something like this:

document.querySelectorAll(".drum").forEach(function(drum){
 drum.addEventListener("click" , function(event){
     console.log(event);
 }) 
})

Upvotes: 0

Andy
Andy

Reputation: 63550

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

Upvotes: 4

Balastrong
Balastrong

Reputation: 4474

document.querySelectorAll(".drum").forEach(el => el.addEventListener("click", handleClick));

You need a forEach to run some code on all elements.

Upvotes: 5

Related Questions