Alvarez
Alvarez

Reputation: 1333

Event listener for few elements at once

Is there a way to add listener for few elements at once?

What I'm doing currently is

$('#test1').on('click', function(event) {
    doSomething();
});
$('#test2').on('click', function(event) {
    doSomething();
});
$('#test3').on('click', function(event) {
    doSomething();
});

As you can see, all three IDs are triggering the same function. How can I combine the code so I won't need to copy code for each listener?

Upvotes: 0

Views: 61

Answers (3)

jerrylow
jerrylow

Reputation: 2629

The best way is to probably select them all if they're a certain type in a container or add a class.

First example:

<div class="box">
  <a href="" id="test1">Test</a>
  <a href="" id="test1">Test</a>
  <a href="" id="test1">Test</a>
</div>

JS:

$('.box a').on('click', function(event) {
    doSomething();
});

Or adding a class:

<a href="" id="test1" class="button">Test</a>
<a href="" id="test1" class="button">Test</a>
<a href="" id="test1" class="button">Test</a>

JS:

$('.button').on('click', function(event) {
    doSomething();
});

Upvotes: 0

kalley
kalley

Reputation: 18462

You can do it like this:

$('#test1, #test2, #test3').on('click', function(event) {
   doSomething();
});


Or add a class to each one and use that:

$('.some-class').on('click', function(event) {
   doSomething();
});


Or for good measure, delegation (assuming they all start with the same thing):

$('body').on('click', '[id^=test]', function(event) {
   doSomething();
});

Upvotes: 3

JaredPar
JaredPar

Reputation: 754575

Why not ...

var all = [ "#test1", "#test2", "#test3" ];
for (var i = 0; i < all.length; i++) { 
  $(all[i]).on('click', function (event) { 
    doSomething();
  });
}

Upvotes: 1

Related Questions