Anton
Anton

Reputation: 12435

How does JQuery's .click() work behind the scenes?

This question is just out of curiosity. I want to know how jquery's .click() works behind the scenes.

For instance if I create a button:

<input type="button" id="myButton" value="Click me!" />

Then I have the following jquery code:

$('#myButton').click( function() {
    alert("I have been clicked.");
});

How does jquery make it so that my function is called when the button is clicked?

At first I thought it would add the onClick="" attribute to the button's tag, but when I inspected the page with Firebug I just saw:

<input type="button" id="myButton" value="Click me!" />

So what does jquery do behind the scenes?

Upvotes: 5

Views: 2612

Answers (3)

Mauricio
Mauricio

Reputation: 5853

the function is attached to the onclick event on your input but not using the html declaration but plain javascript. Instead of looking in the html code take a look at the DOM tab in firebug, you should find it there.

In plain javascript it's like

    document.getElementById('myButton').addEventListener('click',function () { alert('hello!');},false);

Upvotes: 1

user113716
user113716

Reputation: 322502

It will depend on the browser.

If you're using a browser that supports addEventListener(), they'll add a handler using that.

Although I'm pretty sure they're actually attaching a function that first repairs/normalizes the event object, then checks the DOM element for the jQuery12345... property and looks up the handler in jQuery.cache and invokes it.

If you log your element to the console, you'll see a property that looks something like:

jQuery1296081364954: 1

Then if you log that number to the console from jQuery.cache, you'll see the associated data.

console.log(jQuery.cache[1]);

...which will give a structure something like this:

{
   events:{
      click:[
         { /* object containing data relevant to the first click handler */ }
      ]
   },
   handle:{ /* this may be what initially gets called. Not sure. */ }
}

Because jQuery does normalize the event object, it isn't quite as simple as just assigning a a handler for you and calling it. I believe it is also done with the cache in order to avoid memory leaks in older browsers.

Upvotes: 3

Dustin Davis
Dustin Davis

Reputation: 14585

Uses the DOM event model, which is also what happens when you add the onClick(). so basically it registers a listener for the button to fire off the click event and then performs the code you told it to.

Upvotes: 4

Related Questions