0

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?

Alberto Montellano
  • 5,886
  • 7
  • 37
  • 53
  • 1
    possible duplicate of [How to execute a JavaScript function when I have its name as a string](http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string) – James Hill Jul 03 '14 at 18:53
  • Your duplicate proposal refers to how to call a function when you have the name as string, my question is how to call a method using the element: element.function() – Alberto Montellano Jul 03 '14 at 18:58
  • You could just store the elements as a single variable instead. – Popnoodles Jul 03 '14 at 19:51
  • Please, instead of creating an if/else jungle, use `switch`. – Popnoodles Jul 03 '14 at 19:52

1 Answers1

2

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]();
 };
Community
  • 1
  • 1
Mark Silverberg
  • 1,249
  • 2
  • 8
  • 21