Friday 30 August 2019

jQuery same click event for multiple elements



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


Answer



$('.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);

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...