Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining $('body').on('click') with $(window).resize(function() in jQuery

Wondering if there is a way to combine identical code of 2 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)
});
like image 586
Nikita 웃 Avatar asked Dec 23 '15 09:12

Nikita 웃


2 Answers

You can define a single function which you call under both events:

function doSomething(e) {
    console.log('Your code here...');
}

jQuery('body').on('click', '.some_div', doSomething);
jQuery(window).resize(doSomething);

Bear in mind that the reference to this will be different depending on the event raised, should that be used within your doSomething function.

like image 112
Rory McCrossan Avatar answered Oct 19 '22 15:10

Rory McCrossan


You can create a function to handler both the events and pass this function reference to the event handlers.

function myHandler(e) {
    // Long and fancy code
}

jQuery('body').on('click', '.some_div', myHandler);

jQuery(window).resize(myHandler);
like image 44
Tushar Avatar answered Oct 19 '22 13:10

Tushar