Reputation: 115
I would like clicking div-1 and div-2 to do the same thing but please how can I combine the 2 eventlisteners functions into 1
var div_1 = document.getElementById("div-1");
var div_2 = document.getElementById("div-2");
div_1.addEventListener('click', function() {
// clicking div_1 and div_2 does the same thing
});
div_2.addEventListener('click', function() {
// clicking div_1 and div_2 does the same thing
});
Any help would be much appreciated!
Upvotes: 0
Views: 74
Reputation: 478
Just to show another way, without detracting from the very good answers posted.
// we obtain all the elements of this class
let elems = document.getElementsByClassName( 'divs' );
// we iterate between the elements and add a listener
for( let i in elems ) {
elems[i].onclick = function() {
console.log( 'You clicked on interesting div' );
};
}
<!-- we add to the “div” we are interested in, the class we will use to invoke them -->
<div id="div-1" class="divs"> Div 1 </div>
<div id="div-2" class="divs"> Div 2 </div>
<div id="div-3"> Div 3 </div>
Upvotes: 0
Reputation: 436
Select them into a single variable using querySelectorAll
and then give single addEventListener
using loop.
const selectedEls = document.querySelectorAll("#div-1, #div-2");
selectedEls.forEach(function(div) {
div.addEventListener("click", function() {
console.log("All selected Elements(divs) are affected");
});
});
Upvotes: 0
Reputation: 164946
Use event delegation by listening on a common parent element then detect either <div>
using a selector list
document.getElementById('parent').addEventListener('click', ({ target }) => {
const div = target.closest('#div-1, #div-2'); // selector list of IDs
if (div) {
console.log(`You clicked on interesting div '#${div.id}'`);
}
});
#parent {
display: flex;
column-gap: 1rem;
& div {
cursor: pointer;
border: 1px solid;
padding: 1rem;
}
}
<div id="parent">
<div id="div-1">Click me</div>
<div id="div-2">No, click me!</div>
<div id="div-3">You can try clicking me</div>
</div>
Another option would be to use the same selector list and iterate the results of document.querySelectorAll()
but this is less optimal as it repeats the listener function on each element.
document.querySelectorAll('#div-1, #div-2').forEach((div) => {
div.addEventListener('click', (e) => {
console.log(`You clicked on interesting div '#${div.id}'`);
});
});
Upvotes: 1
Reputation: 5494
There are several ways you can do this. Here is one option: Use a named function and pass it as a event handler to both the addEventListener
's.
Ex:
const clickHandler = function(e) {}
div_1.addEventListener('click', clickHandler)
div_2.addEventListener('click', clickHandler)
Upvotes: 0