Reputation: 6246
I would like to create a function that receives another function as parameter and then call this function in an element, like this:
function applyFunctionToDivs(function1, function2, function3) {
$('#div1').function1();
$('#div2').function2();
$('#div3').function3();
};
Is there a jQuery / Javascript way to do this directly?
I accomplished this but creating additional functions like this:
if (value == 'A') {
applyFunctionToDivs(showElement, hideElement, hideElement);
}
if (value == 'B') {
applyFunctionToDivs( hideElement,showElement, hideElement);
}
if (value == 'C') {
applyFunctionToDivs(hideElement, hideElement, showElement);
}
My functions to show/hide:
function showElement(elem) {
elem.show();
};
function hideElement(elem) {
elem.hide();
};
function applyFunctionToDivs(fun1, fun2, fun3) {
fun1($('#div1'));
fun2($('#div2'));
fun3($('#div3'));
};
I think this could be optimized. Any suggestion to do this directly?
Upvotes: 0
Views: 72
Reputation: 1259
From https://stackoverflow.com/a/11356926/252671, you can do the following:
$("body")['function']()
So you could do the following but it could be further refactored to make the argument into an array and loop through the array.
function applyFunctionToDivs(function1, function2, function3) {
$('#div1')[function1]();
$('#div1')[function2]();
$('#div1')[function3]();
};
Upvotes: 2