9

I have 2 html button named Button1 and Button2.

The two button performs same operation using jquery.

now i wrote the same jquery in click event of both buttons.thats shown below

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



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

The both jquery are same. Can i catch the click event of both button in single function?

Null Pointer
  • 9,089
  • 26
  • 73
  • 118

3 Answers3

22

You can use a multiple selector:

$('#Button1, #Button2').click(function() {
    // You can use `this` to refer to the source element, for instance:
    $(this).css("color", "red");
});
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
2

I would use a class on the buttons:

$('.className').click(function() {
    var item = $(this); // item that triggered the event

});
Andrew
  • 9,967
  • 10
  • 64
  • 103
2

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

function handleClick() {
    // Do something..
}

$('#Button1').click(handleClick);
$('#Button2').click(handleClick);

Hope this helped.

Kevin
  • 5,626
  • 3
  • 28
  • 41