Home > OS >  Jquery combine on click Eventhandler
Jquery combine on click Eventhandler

Time:12-24

I have a little link routine that intercepts every link on the web and processes it accordingly.

How can I combine the following two jquery event handlers into one EventHandler?

$("body").on("click", "a", function (e) {
 //call function
};



// mobile links
$("#Mobile a").on("click", function (e) {
 //call same function
});

CodePudding user response:

Try this:

$('body, #Mobile a').on('click', someFunction);

or

$('body').add('#Mobile a').on('click', someFunction);

Now the function part

function someFunction(){
    // Your code here
}

CodePudding user response:

Type 1: You may define function and then pass as a argument

function myClickEventHandler(e) {
  
}

$("body").on("click", "a", myClickEventHandler);

// mobile links
$("#Mobile a").on("click", myClickEventHandler);

Type 2: You may like to update selector(pass multiple selector by separating comma )

$("body").on("click", "a, #Mobile a", function (e) {
 //call function
};
  • Related