Access click event for two buttons using jquery

I have 2 html buttons named Button1 and Button2.

Two buttons perform the same operation using jquery.

now I wrote the same jquery in the click event for both buttons. This is shown below.

$('#Button1').click(function () { xyz //some jquery }) $('#Button2').click(function () { xyz //some jquery }) 

Both jquery are the same. Can I catch the click event for both in one function?

+6
jquery
source share
3 answers

You can use multiple selector :

 $('#Button1, #Button2').click(function() { // You can use `this` to refer to the source element, for instance: $(this).css("color", "red"); }); 
+15
source share

I would use a class on buttons:

 $('.className').click(function() { var item = $(this); // item that triggered the event }); 
+2
source share

Declare a function and use it as a parameter. For instance:

 function handleClick() { // Do something.. } $('#Button1').click(handleClick); $('#Button2').click(handleClick); 

Hope this helped.

+1
source share

All Articles