3

I've been shown how to call variable javascript functions by using window[]().

Is it possible to call variable jQuery functions? If so, how?

Usually, I only need a ternary to flip a visible switch, and it would be very convenient to smush many lines of code into 1. For example, inside an $.aja() success:

if(msg.length > 0){
    $("#gridViewContainer").slideDown()
}
else{
    $("#gridViewContainer").slideUp()
}

This is probably a bad example since a boolean can probably be passed to slide() or something, but I'd like to use the concept in the linked question above.

This did not work for me:

$("#gridViewContainer")[((msg.length > 0)?'slideDown':'slideUp')]()
7
  • 2
    What do you mean by "call variable jQuery functions"? Could you give an example? Commented Sep 18, 2013 at 17:59
  • jQuery functions are javascript functions, since jQuery is javascript. Commented Sep 18, 2013 at 18:00
  • sure, x="hide"; $(selector)[x]() Commented Sep 18, 2013 at 18:00
  • 1
    @Gracchus Post a fiddle that demonstrates the issue. Commented Sep 18, 2013 at 18:02
  • 1
    @Gracchus Here's (for the most part) your example working: jsfiddle.net/zavSb Commented Sep 18, 2013 at 18:11

1 Answer 1

6

jQuery functions are still just JavaScript functions, so the same rules apply to them as any other JS functions.

You can call methods of an object objectVar as follows:

objVar.method();
objVar["method"]();
var methodName = "method";
objVar[methodName]();

Your question mentioned using window[]() - that applies to global functions, since they are essentially properties of window (if running JS in the browser, of course).

In the case of jQuery, you can therefore do this:

var methodName = "hide";
$(someSelector)[methodName]();
$(someSelector)[anyJSExpressionThatReturnsAStringThatIsAjQueryMethod]();

EDIT: I just saw the new version of the question. The line of code shown with the ?: operator selecting the method name should give the same effect as the if/else. I've used similar code myself with no problems, and it works fine in the fiddle that Jason P provided. Note that since your motivation here seems to be about making the code shorter you can omit all of the parentheses from the expression in the [] and just do this:

$("#gridViewContainer")[msg.length > 0?'slideDown':'slideUp']();

...or even omit the > 0 part since msg.length will be truthy when non-zero:

$("#gridViewContainer")[msg.length ?'slideDown':'slideUp']();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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