As I understand it:
When you use live()
an event handler is attached to the document
.
Why?
Given this snippet:
<html>
<body>
<ul>
<li><a href="#">my link</a></li>
</ul>
</body>
</html>
When you click or move the mouse on the <a>
tag, you have to remember that your <a>
is sitting inside an <li>
which is inside a <ul>
in a <body>
in <html>
which is inside the document
. No matter what HTML structure you have, every element exists within the document
.
So, when you click the link, you're actually also clicking all those other elements too, it's just that the link is sitting on top*
of that stack. This is called bubbling - the click event starts on the link and bubbles up through each of its parents finally reaching the document
. Any time you click any element you're also clicking the document
.
Therefore, if you place an event listener on the document
to handle clicks, it can check where else was clicked in that same event before it bubbled to the document
. The live()
function simply stores the query string you provided and compares that against all clicked (or mousemove
d, etc) elements and fires your function if it gets a hit.
The others: blur
, focus
, mouseenter
, mouseleave
, change
, submit
are all events which don't bubble, therefore they can't be used with live()
.
Why don't they bubble?
Because if you think about it, it doesn't make sense. If you focus an element, you are only focusing one element, not its parents and ancestors. Similarly with the others - the events never reach the document so you can't use this technique.
*
: as with many "tree" metaphors in computing, terms like "up" and "top" can be a bit confusing. Though your link is visually rendered at the top, it's probably more helpful to think of it as at the bottom. The events bubble upwards through parents and reach the top level element which is the "root". :-/