JQuery onClick multiple callbacks

How to register multiple callbacks for jQuery event? An example of what I'm trying to achieve:

$(document).on("click", ".someclass", CallbackFunction1, CallbackFunction2); function CallbackFunction1(event) { //Do stuff } function CallbackFunction2(event) { //Do some other stuff } 

How can I configure an event handler to perform both callback functions when an element is clicked?

+6
source share
4 answers

You can simply attach them as separate event handlers:

 $(document).on("click", ".someclass", CallbackFunction1) .on("click", ".someclass", CallbackFunction2); 
+9
source

If I do not understand what you are asking, you can use one event handler:

 $(document).on('click', '.someclass', function(e){ CallbackFunction1(e); CallbackFunction2(e); }); 
+4
source

If you reuse this to bind a different list of handlers for different elements, I would create a factory.

 function multiFunction(){ var methods = Array.prototype.slice.call(arguments, 0); return function(e){ for (var f=0, l = methods.length; f<l; f++) { methods[f].apply(this, arguments); } } } 

and call it as follows

 $(document) .on('click', 'someclass', multiFunction( CallbackFunction1, CallbackFunction2)); .on('click', 'someotherclass', multiFunction( CallbackFunction8, CallbackFunction1, CallbackFunction5)); 

Demo at http://jsfiddle.net/gaby/D8K75/

0
source

You can use the third function and then call others:

 $(document).on("click", ".someclass", CallbackFunction); function CallbackFunction(event) { CallbackFunction1(event); CallbackFunction2(event); } function CallbackFunction1(event) { //Do stuff } function CallbackFunction2(event) { //Do some other stuff } 
-1
source

Source: https://habr.com/ru/post/973368/


All Articles