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?
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
});
});
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');
}
})
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
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With