Reputation: 809
I wrote a function that works great for mobile, based on something I found on SO a while ago.
jQuery(document).on('touchstart', function(event) {
if ( !jQuery(event.target).closest("#peopleMenu").length) {
jQuery("#peopleMenu").fadeOut();
}
});
the part that I found was in the "if" statement that took me a bit to wrap my head around.
It is saying that if the target touch event is on #peopleMenu , it will stay open, or close if touched off. The if statement boils down to :
if (!1) {
//false - understand this.
}
if (!0) {
//true - hmmm.
}
My question is basically is this a common programming paradigm, a strange js feature, or is it just trickier than it needs to be? Thanks.
Upvotes: 0
Views: 52
Reputation: 33880
It is common, it mean if you touch something else than #peopleMenu
or its childrens, do something.
0
is a falsy value while every other integer are truthy.
Using bang (!
) reverse the value, !true == false
and !false == true
.
The .length
property of jQuery is the way to know how many element are selected. 0 mean none.
Upvotes: 1
Reputation: 976
This is common in many languages. Everything in JavaScript has an inherent Boolean value, generally known as either truthy or falsy.(e.g. 0 or an empty string). So in this case, if the length comes back as 0, the if statement is false. Here is a great writeup on this topic as it relates to Javascript if you care to know more: Truthy/Falsy
Upvotes: 1