hsuk
hsuk

Reputation: 6860

jQuery different events on different elements to trigger the same function

What if different elements have to trigger the same function but on different events ?

$('#btnNext').on('click', function() { /*Same thing*/ });

$('#txtField').on('change blur', function() { /*Same thing*/ });

Is there any way to integrate these two lines, so I can write the same lines of code just once ?

Upvotes: 2

Views: 1367

Answers (3)

Rohith Gopi
Rohith Gopi

Reputation: 566

Here is a jsFiddle For You

Fiddle Here

 function Commonalert(){alert("Common Alert Message");}

$('#Btn').on('click', Commonalert);

$('#text').on('change blur', Commonalert);

Upvotes: 1

Harsha Venkataramu
Harsha Venkataramu

Reputation: 2904

$('#btnNext').on('click', myMethod );

$('#txtField').on('change blur',  myMethod );

function myMethod()
{
/*Your Code goes here*/
}

Upvotes: 3

nnnnnn
nnnnnn

Reputation: 150010

You included a clue in your question: "trigger the same function" - so simply bind the same function:

function commonHandler(e) { /* your code */ }

$('#btnNext').on('click', commonHandler);

$('#txtField').on('change blur', commonHandler);

Upvotes: 9

Related Questions