Matoeil
Matoeil

Reputation: 7309

Add same event listener function to more than one element

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){

Upvotes: 2

Views: 462

Answers (1)

spanky
spanky

Reputation: 2880

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');
}

Upvotes: 9

Related Questions