Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

add click event to multiple items JavaScript

//HTML
 <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>

    <script src="index.js"></script>
  </body>

//JavaScript
//number of elements with class of drum
var numOfDrumButtons = document.querySelectorAll('.drum').length;
//assigning the buttons to an array called drums
var drums = document.querySelectorAll('.drum');
//using a for loop to iterate through each arrayed element
for (var i = 0; i < numOfDrumButtons; i++) {
  //each array indexed and assigned an anonymous function with alert
  drums[i].addEventListener('click', function () {
    alert('I got clicked');//for testing
    //add actions to occur upon click hear
  });
}
Comment

can you have multiple onclick events

<input type="button" value="test" onclick="Hey(); Ho();" />
Comment

javascript addeventlistener click multiple elements

let all_btn = document.querySelectorAll("button");
all_btn.forEach(function(btn) {
    btn.addEventListener("click", function() {
        console.log(this.innerHTML + " is clicked")
    });
});

// one line code
// let all_btn=document.querySelectorAll("button");all_btn.forEach(function(n){n.addEventListener("click",function(){console.log(this.innerHTML+" is clicked")})});
Comment

PREVIOUS NEXT
Code Example
Javascript :: react native navigation nested 
Javascript :: expo app loading 
Javascript :: import syntax node 
Javascript :: fs.readdir callback function 
Javascript :: capitalize first letter 
Javascript :: image file size in react-dropzone 
Javascript :: check object has key 
Javascript :: jquery append to table 
Javascript :: this.handler.handle is not a function 
Javascript :: groupBy angular 
Javascript :: js months ago 
Javascript :: Creating URL Search Parameters From An Array 
Javascript :: js .then mean 
Javascript :: mutable array methods in javascript 
Javascript :: javascript shift everything in array to the right 
Javascript :: mongoose in node.js 
Javascript :: golang json omitempty struct 
Javascript :: observable filter angular 8 
Javascript :: square element in array 
Javascript :: react memo 
Javascript :: jquery selector id ends with 
Javascript :: jspdf create table 
Javascript :: how to use useeffect 
Javascript :: jsx babel webpack 
Javascript :: angular cli generate guard 
Javascript :: express referrer 
Javascript :: reverse keys and values in object javascript 
Javascript :: javascript child element selector 
Javascript :: async function javascript 
Javascript :: change image on click javascript 
ADD CONTENT
Topic
Content
Source link
Name
2+4 =