The union of $ ('body'). On ('click') with $ (window) .resize (function () in jQuery

I wonder if there is a way to combine identical code from two separate functions into 1 function.

In my case:

jQuery('body').on('click', '.some_div', function (e) { // Long and fancy code }); jQuery(window).resize(function () { // Do the same fancy stuff (identical code) }); 
+7
javascript jquery
source share
4 answers

You can define one function that you call in both cases:

 function doSomething(e) { console.log('Your code here...'); } jQuery('body').on('click', '.some_div', doSomething); jQuery(window).resize(doSomething); 

Remember that the reference to this will be different depending on the event raised, if it will be used in your doSomething function.

+14
source share

You can create a function to handle both events and pass this link to the function event handlers.

 function myHandler(e) { // Long and fancy code } jQuery('body').on('click', '.some_div', myHandler); jQuery(window).resize(myHandler); 
+5
source share

There is another way to do this.

 jQuery('body').on('click', '.some_div', function (e) { // Long and fancy code }); jQuery(window).resize(function () { $('.some_div').trigger('click') }); 
+4
source share

create a separate function and call it from the required places:

 jQuery('body').on('click', '.some_div', function(e){ myFunction(); }); jQuery(window).resize(function() { myFunction(); }); function myFunction(){ // Long and fancy code } 
+3
source share

All Articles