Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't jQuery 1.3.3. live() support all events?

I've just been pondering the jQuery live() event binder, which seems like a really useful function.

http://docs.jquery.com/Events/live

One thing I note is that it doesn't support all events:

"Currently not supported: blur, focus, mouseenter, mouseleave, change, submit"

My (very simple) mind reasons that surely if it were implemented for one event, it would be easy to do it for all others?

Clearly its wasn't that simple, so I wondered if anyone knows why it was so difficult to do it for all others?

like image 518
James Wiseman Avatar asked Dec 22 '22 09:12

James Wiseman


2 Answers

This is because it uses event delegation. The problem is that event delegation based on event bubbling. And events are bubbling not for all events.
you can read more here: JavaScript Event Delegation is Easier than You Think

like image 171
Eldar Djafarov Avatar answered Dec 26 '22 20:12

Eldar Djafarov


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 mousemoved, 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". :-/

like image 34
nickf Avatar answered Dec 26 '22 18:12

nickf