0

Here is a very very very simplified example.

I am trying to pass a function name "show" or "hide" as a parameter.

but it wont work , can you please help?

if(a==true){
showOrhide (hide);
}else{
showOrhide (show);
}

var showOrhide = function(doThis){
  $("#myDiv").doThis();
};
scunliffe
  • 62,582
  • 25
  • 126
  • 161
Hello-World
  • 9,277
  • 23
  • 88
  • 154
  • possible duplicate of [JavaScript object: access variable property by name as string](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string) – Felix Kling Aug 16 '13 at 12:41

3 Answers3

3

It would work like this:

var showOrhide = function(doThis) {
    $("#myDiv")[doThis]();
};

if(a) {
    showOrhide('hide');
} else {
    showOrhide('show');
}

Hoever, it's still extremely ugly. jQuery has a toggle() method that accepts a boolean argument which would be much more appropriate:

$("#myDiv").toggle(!a);
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

If you want only pass show and hide functions you could pass only their names and call them in that way:

if(a==true){
  showOrhide ('hide');
}else{
  showOrhide ('show');
}

function showOrhide (doThis){
  $("#myDiv")[doThis]();
};
Naftali
  • 144,921
  • 39
  • 244
  • 303
Setthase
  • 13,988
  • 2
  • 27
  • 30
  • @Neal why do you think so? – Setthase Aug 16 '13 at 12:42
  • This should work, because of hoisting: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html – Setthase Aug 16 '13 at 12:44
  • @codename- Hoisting makes sure the variable is declared, but it doesn't hoist the definition (in case of the original answer which had the `var showOrhide = ...`) – JJJ Aug 16 '13 at 12:45
-2

Disclaimer : Eval is evil (Quoting comments). Please use it on your own risk. Following answer is just for knowledge purpose. :-)

Another way, using eval.

var showOrhide = function(doThis){
  eval("$('#myDiv')." + doThis + "()");
};    

if(false==true){
  showOrhide ('hide');
}else{
  showOrhide ('show');
}
Jithin
  • 2,594
  • 1
  • 22
  • 42
  • I know the best methods are using `toggle()` and then `$("#myDiv")[doThis]();`. And thats why I started the answer with an Or. I just posted another method to achieve the requirement. and @Juhana : Thanks :-) – Jithin Aug 16 '13 at 12:50
  • 1
    *"thanks I never new this - cool I learned something"* --- and that's why, @Jithin, it's better not to talk about eval without heavy use of disclaimers because the actual use cases are so far and between that there's a good chance the OP will shoot themselves in the foot using it someplace else. – JJJ Aug 16 '13 at 13:17