Signup/Sign In

Use same Click Event Handler for different Class in jQuery

If you use jQuery for handling events in your HTML webpage like handling click, blur, keyup, etc. events, you must be using either the element selector, id selector, or class selector to identify the events on HTML elements.

If you use a class selector to handle a click event, then for all the HTML elements with that class, the click event will be handled in the same event handler function.

For example, if the HTML code is:

<div class="myClass">Some text...</div>
<button class="myClass">Some button</button>

and the jQuery code is:

$('.myClass').click(function() {
    // event handling
});

The above click event handler will handle the click event for both div element and button element defined in our HTML code.

This is the default behaviour for class selector event handling when the class name is the same for multiple elements.

But what if you want to use the same event handler function for different classes?

Use Event Handler function for different classes:

If we want to use the same event handler function for more than one class, we can also do it in jQuery.

Let's take an example to understand it. If the HTML code is following:

<div class="myClass1">Some text...</div>
<button class="myClass2">Some button</button>

In the above code, the div element has class myClass1 and the button element has class myClass2.

So, if we want to use the same event handler, we can do it as follows:

$('.myClass1, .myClass2').click(function(){
    // event handling
});

Just like the click event, we can handle any jQuery event for different classes in this way.

Using the add() function:

We can also use the add() function to add multiple class names for event handling.

The following syntax will also work:

$('.myClass1').add('.myClass2').click(function(){
    // event handling
});

We can chain multiple class elements this way.

It is recommended to use the on() event handler in jQuery.

Conclusion:

While we can use multiple event handlers for different class, but if absolutely same operation is performed on click of two or more class selectors, then it is good to reuse the same code.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight