jQuery onClick multiple callbacks
11,813
Solution 1
You can just attach them as separate event handlers:
$(document).on("click", ".someclass", CallbackFunction1)
.on("click", ".someclass", CallbackFunction2);
Solution 2
Unless I misunderstand what you're asking, you can use a single event handler:
$(document).on('click', '.someclass', function(e){
CallbackFunction1(e);
CallbackFunction2(e);
});
Author by
nagyben
Updated on June 17, 2022Comments
-
nagyben almost 2 years
How do I register multiple callbacks for a jQuery event? An example of what I am trying to achieve:
$(document).on("click", ".someclass", CallbackFunction1, CallbackFunction2); function CallbackFunction1(event) { //Do stuff } function CallbackFunction2(event) { //Do some other stuff }
How can I set up the event handler to execute both callback functions when the element is clicked?
-
DoXicK almost 10 yearswe could go even deeper and call it 'func-ception'! ;-)
-
cookie monster almost 10 yearsThat implementation lacks a few things. It doesn't set the
this
value of the functions, it doesn't handle return values, and it doesn't check to see if immediate propagation was stopped between calls. -
DoXicK almost 10 yearsYup, i know. I didn't downvote either though. I just upvoted Vatev's answer since that is the most elegant (and correct) solution in this case :-)
-
Gabriele Petrioli almost 10 years@cookiemonster right.. was testing something else before that solution and it stuck.. also changed
call
toapply
so that it can pass all arguments supported by event. -
Brutus almost 10 yearsSure, I totally agree with you and was just trying to justify my answer! Anyway I really appreciated the term "func-ception", I'll remember that forever!!! :D Respect++ for you! :D
-
nagyben almost 10 yearsDid just that. Thank you very much!
-
nagyben almost 10 yearsDon't know why you got downvoted because this works too
-
DoXicK almost 10 years@exantas the reason this got downvoted is because it's a bad practice to do this ánd, as can be read in the comments on AJM's response :-) Putting a nail into a wall with your head doesn't make it a hammer... it makes it very sore. But it does work!
-
dgo about 7 years@cookiemonster : A way to get
this
and allow for return values (that you wouldn't really work with on click event handler as such anyway) would be:CallbackFunction1.apply(this,[e]); CallbackFunction2.apply(this,[e])
. I use this methodology often even if only need a single callback. It allows me to decouple my callbacks from relying too heavily on the type of event that generates them. -
Zach Smith over 6 yearsI am trying this, but I find that if I register about 40 callbacks that performance seriously deteriorates (functions take as long as 10 seconds to start executing)
-
Vatev over 6 yearsI just tried adding a lot of click listeners at document.body on this page via the console, and didn't see any noticeable slowdown. There is something specific to your setup which causes it.