Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 607
Anton Avatar asked Jan 26 '11 22:01

Anton


2 Answers

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.

like image 184
Dustin Davis Avatar answered Sep 22 '22 09:09

Dustin Davis


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.

like image 29
user113716 Avatar answered Sep 21 '22 09:09

user113716