views:

72

answers:

1

With a div on an HTML page, I used jQuery to add a click event handler:

  $(document).ready(function(){    

      $("div").click(function() { alert("clicked!"); });

  });

Then I used the Visual Studio 2008 (or IE8) debugger to step through the javascript/jquery. I expected to see a value in the debugger for:

$(“div”)[0].onclick

($(“div”)[0] being the first div in the collection of results of the selector, $(“div”)).

But I don’t. I thought jQuery’s event assignment methods (e.g., .click(function)) were actually assigning values to an element’s underlying events. They’re not?

In other words, these two lines of code don’t have the same affect, but I thought they would:

$("div").click(function() { alert("clicked!"); }); // (Line 1)
$("div")[0].onclick = function() { alert("clicked!"); }; // (Line 2)

Can anyone explain this or point out if I’m doing something wrong? I would like to use line 1 in my code, but for my needs it seems I’ll have to use line 2 (FYI, I am planning to use an actual function, and not just show alerts :-) ).

Thank you

A: 

jQuery does not use the onclick attribute to attach events to elements. It uses either attachEvent(IE) or addEventListener(all others). You can find the smoking gun in lines 2500-2502 of the uncompressed jquery-1.3.2.js.

You should be able to, however, place a breakpoint inside your jQuery event handler and have Visual Studio stop there. Either click inside the body of the event handler (e.g. on "alert") before hitting F9, or break the event handler body into a its own line, e.g.

$(document).ready(function(){    
    $("div").click(function() {
        alert("clicked!"); // place a breakpoint on this line
    });
});
Oren Trutner
Thank you. The difference between attachEvent()/addEventListener() and the onclick/onsubmit attribute is what I needed to know. I've also downloaded the "dev" version of jQuery and looked at those lines of code, 2500-2502. I've done some experimenting and come to a better understanding.Now I'm just not sure why we even have the onclick attribute, in addition to, and completely separate of, a set of event handlers. If onclick represented the list of handlers, and we could use: onclick += function(), and/or attachEvent(), that might explain it to me, but that's not it.
Jeremy
onclick is indeed inconsistent with- and less powerful than attachEvent and addEventListener. It is there for historical reasons -- it was there first. The methods were added later, as DOM developers were coming to grips with the needs to separate code from markup and for multiple handlers per element/event.
Oren Trutner
That makes sense. Thanks.
Jeremy