Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to addEventListener to multiple elements in a single line

Tags:

javascript

dom

Example 1:

element1.addEventListener("input", function() {
this function does stuff 
});

Example 2:

element1 && element2.addEventListener("input", function() {
this function does stuff
});

It might not be correct grammatically, but is there a way I can give two elements the same event listener at the same time (same line) instead of having to write them apart?

like image 572
Jamisco Avatar asked Dec 04 '16 08:12

Jamisco


3 Answers

Well, if you have an array with the elements you could do:

let elementsArray = document.querySelectorAll("whatever");

elementsArray.forEach(function(elem) {
    elem.addEventListener("input", function() {
        //this function does stuff
    });
});
like image 67
GMaiolo Avatar answered Oct 07 '22 00:10

GMaiolo


Event Bubbling is the important concept in javascript, so if you can add event on DOM directly, you can save some lines of code, no need for looping :

document.addEventListener('click', function(e){
  if(e.target.tagName=="BUTTON"){
   alert('BUTTON CLICKED');
  }
})
like image 25
Ayush Sharma Avatar answered Oct 06 '22 23:10

Ayush Sharma


If you don't want to have a separate elementsArray variable defined you could just call forEach from an unnamed array with the two elements.

[ Element1, Element2 ].forEach(function(element) {
   element.addEventListener("input", function() {
      this function does stuff
   });
});
like image 30
John Ayling Avatar answered Oct 07 '22 01:10

John Ayling