How to addEventListener to multiple elements in a single line
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?
Solution 1:
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
});
});
Solution 2:
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');
}
})
Solution 3:
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
});
});