1

Is there a way to call methods by their name in jQuery? For example:

var condition = true;
$('div').execute(condition ? 'show':'hide');
1
  • What is it you are trying to do? It may be that there is a better solution not involving dictionary based access of methods. Commented Jul 6, 2011 at 11:40

2 Answers 2

4

Yes, use the []notation to access properties of the jQuery object (rather than literal ones using .):

$('div')[condition ? 'show' : 'hide']();

You can also do:

$('div').toggle(condition);

http://api.jquery.com/toggle/

http://www.jibbering.com/faq/faq_notes/square_brackets.html

Edit: Just in case you prefer your own style of coding, you could add this:

$.fn.execute = function(a) {
    return this[a].apply(this, [].slice.call(arguments, 1));
}

Then you can do like:

$('div').execute(condition ? 'show' : 'hide');

or

$('div').execute(condition ? 'keydown' : 'keyup', function() {...});
Sign up to request clarification or add additional context in comments.

1 Comment

@Dziamid: I use .toggle mostly, because it's clearer to read.
2

Javascript objects are basically dictionaries.

var condition = true;
$('div')[condition ? 'show':'hide']();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.