6

I need to call a function in the following fashion:

var f = 'fadeOut';
$(v).f(s, function(){
    $(v).css('visibility', 'hidden').css('position', 'absolute');
});

Is this possible to do simply?

nick
  • 2,743
  • 4
  • 31
  • 39
  • Please have a look at the following link http://stackoverflow.com/questions/3619046/javascript-variable-function-name. It's not the same question exactly, but I feel it may prove useful. – Chetter Hummin Apr 06 '12 at 05:01
  • possible duplicate of [How do I call a JavaScript function name using a string?](http://stackoverflow.com/questions/496961/how-do-i-call-a-javascript-function-name-using-a-string) , Call a function in JavaScript by its name? , etc. –  Apr 06 '12 at 05:27

1 Answers1

9

Yes

var f = 'fadeOut';
$(v)[f](s, function(){
    $(v).css('visibility', 'hidden').css('position', 'absolute');
});
Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • Any property of an object can be accessed with dot-syntax or square brackets. The latter though the only way to use if the property contains spaces or other disallowed characters – Boris S Apr 06 '12 at 05:07
  • @BorisShemigon You are correct, however you cannot access a property with dot syntax via a string variable, in that case you must use brackets or utilize `eval` which I do not recommend. – Quintin Robinson Apr 06 '12 at 05:09