Reputation: 53
I ran into this line of code and I can't figure out what it means:
$("#theAppContainer")[s > u ? "addClass" : "removeClass"]("something");
I understand the first part is selecting the element called theAppContainer and the second part evaluates to "addClass" if s > u, but I can't figure out what this line of code does overall.
Upvotes: 5
Views: 1138
Reputation: 206007
Square Bracket notation.
$('#element')['hide'](700)
Dot notation:
$('#element').hide(700)
the other thing ( ? : ) is called ternary operator
that makes a statement comparison returning a boolean value,
Where s>u
is a statement, and depending on the result the values are used:
STATEMENT ? IF TRUE USE THIS : IF FALSE USE THAT ;
if s > u
use 'addClass'
else use 'removeClass'
which means that you'll get $("#theAppContainer")["addClass"]("something");
if s > u
and
$("#theAppContainer")["removeClass"]("something");
if s===u || s<u
which can be translated in DOT notation in:
$("#theAppContainer").addClass("something");
or
$("#theAppContainer").removeClass("something");
This is not the best way to do it, cause you can use toggleClass()
method in that particular case, but any way it's good to know.
And it's not true that you should not use bracket notation. In advanced JS you'll see all the benefits.
Upvotes: 1
Reputation: 224855
The bracket syntax gets the value of a property by name, and the parentheses call the function that is the value of that property. It’s equivalent to:
var container = $('#theAppContainer');
if(s > u) {
container.addClass('something');
} else {
container.removeClass('something');
}
Also, please never write code like that. =)
Also also, toggleClass
takes a second switch
argument that you can use instead:
$('#theAppContainer').toggleClass('something', s > u);
Upvotes: 13
Reputation: 17279
$("#theAppContainer")
returns a jquery object.
jqueryObject["addClass"]
is synonymous with jqueryObject.addClass
So, jqueryObject["addClass"]
returns the addClass method on the jquery object.
Then you use ("something")
to pass parameters into and execute the method.
So you're essentially doing
var myJqueryObject = $("#theAppContainer");
if(s > u) {
myJqueryObject.addClass("something");
}
else {
myJqueryObject.removeClass("something");
}
Upvotes: 5