Reputation: 1333
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
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
Reputation: 18462
You can do it like this:
$('#test1, #test2, #test3').on('click', function(event) {
doSomething();
});
$('.some-class').on('click', function(event) {
doSomething();
});
$('body').on('click', '[id^=test]', function(event) {
doSomething();
});
Upvotes: 3
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