Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add same event listener function to more than one element

Tags:

javascript

document.getElementById("composantes").addEventListener("click", function(event){
    event.preventDefault();
    var selector = $(this);
    console.log('click'+selector.attr('id'));
    ToggleLocalStorage(selector,'expanded');
});

Here is my code, I would like it to work for more than one id, like:

document.getElementById("composantes, campus, public_target").addEventListener("click", function(event){
like image 535
Matoeil Avatar asked Dec 05 '25 09:12

Matoeil


1 Answers

You can use querySelectorAll. Also probably good to use a named function so that you're not creating more identical functions than needed. It's also helpful if you need to unbind the handler.

const els = document.querySelectorAll("#composantes, #campus, #public_target");
for (const el of els) {
  el.addEventListener("click", handler);
}

function handler(event) {
  event.preventDefault();
  console.log('click', this.id);
  ToggleLocalStorage($(this),'expanded');
}
like image 153
spanky Avatar answered Dec 07 '25 23:12

spanky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!