This is the code from the answer in that other question:
$(document).mouseup(function (e)
{
var container = $("YOUR CONTAINER SELECTOR");
if (container.has(e.target).length === 0)
{
container.hide();
}
});
First thing you need to know is how events in the browser work. In most cases, they "bubble" from the element that initially triggered the event all the way up, through its ancestor elements, to the document itself; this process is known as event propagation.
So, if you had this HTML:
<body>
<div>
<a href="#">Click me!</a>
</div>
</body>
Then clicked on the <a>
element, the event will be triggered by that <a>
element, but bubble to the <div>
, then to the <body>
, then to the <document>
.
If you bind an event handler to the document
, then clicking on the anchor is still going to trigger that event handler function, because the event bubbles up and is finally handled by the document. This is the underlying principle of the code above.
Now, let's look at the actual event handler function. You have a single argument, e
, which is the event itself. That object has a property, target
, that is the element that initially triggered the event.
Going back to our simple HTML example, if you click on the <a>
element then e.target
will be that anchor, even when the event is being handled at the document level. This differs from this
inside jQuery event handler functions, which will be the element handling the event (in this case, document
).
The first line is pretty straight forward - it just selects the element you want to ignore clicks inside of.
The if
statement is where it gets a bit tricky, but it's essentially saying "If the element that initially triggered this event isn't a descendent of our container, hide our container".
The container.has(e.target)
part is checking "Is the element that triggered the event inside our container?". If the answer to that is "yes", then the length
property is going to be greater than 0
(to be precise, it will be 1
since we started with a jQuery object containing a single element).
If the answer is "no", the length
property is going to equal 0
. Since this is what we actually want to check for, we compare the length
property to 0
in our if
condition.