danronmoon
danronmoon

Reputation: 3873

How does jQuery listen for DOM events being fired?

How does jQuery know when any DOM event happens?

$('body').on('click', function(e) {
    alert('working');
});

document.body.onclick; // null

I rely on this library way too much. Can someone tell me how it knows when the body is clicked?

Upvotes: 2

Views: 342

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191729

.on wraps jQuery.event.add (if you look at the jQuery source that is on line 2688).

This attempts to use a cached version of the event type, but if there is none it eventually boils down to calling the browser-specific functions for attaching events (on around line 2767).

if ( elem.addEventListener ) {
    elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
    elem.attachEvent( "on" + type, eventHandle );
}

It doesn't seem to have a fallback for the case of neither of these, so the on* attributes are never written to. Hence, elem.onclick will be empty if you use jQuery.on

For reference: http://code.jquery.com/jquery.js

Upvotes: 3

gdoron
gdoron

Reputation: 150253

jQuery (thanks God) doesn't use the onclick attribute or property of the DOM element, instead it uses the addEventlistener or IE- attachEvent

Upvotes: 3

Related Questions