Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery same click event for multiple elements

Tags:

jquery

events

Is there any way to execute same code for different elements on the page?

$('.class1').click(function() {
   some_function();
});

$('.class2').click(function() {
   some_function();
});

instead to do something like:

$('.class1').$('.class2').click(function() {
   some_function();
});

Thanks

like image 883
Kelvin Avatar asked Aug 21 '09 17:08

Kelvin


4 Answers

$('.class1, .class2').on('click', some_function);

Or:

$('.class1').add('.class2').on('click', some_function);

This also works with existing objects:

const $class1 = $('.class1');
const $class2 = $('.class2');
$class1.add($class2).on('click', some_function);
like image 147
Eevee Avatar answered Sep 25 '22 06:09

Eevee


I normally use on instead of click. It allow me to add more events listeners to a specific function.

$(document).on("click touchend", ".class1, .class2, .class3", function () {
     //do stuff
});
like image 38
bzin Avatar answered Sep 22 '22 06:09

bzin


$('.class1, .class2').click(some_function);

Make sure you put a space like $('.class1,space here.class2') or else it won't work.

like image 37
coolguy Avatar answered Sep 23 '22 06:09

coolguy


Simply use $('.myclass1, .myclass2, .myclass3') for multiple selectors. Also, you dont need lambda functions to bind an existing function to the click event.

like image 27
code_burgar Avatar answered Sep 25 '22 06:09

code_burgar