39

What's the difference between the following two pieces of HTML (apologies if there are any typos as I'm typing this freehand)?

Using jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        $("#clickme").click(function() {
            alert("clicked!");
        });
    });
</script>

<a id="clickme" href="javascript:void(0);">click me</a>

Not using jQuery:

<a id="clickme" href="javascript:void(0);" onclick="alert('clicked!');">click me</a>
2
  • 1
    Just a note: you should never ever put JavaScript code in the href attribute. It creates links that do nothing on non-JavaScript enabled browsers, and breaks the idea of progressive enhancement (or graceful degradation if you will). Commented Apr 8, 2011 at 7:12
  • 3
    @Joseph Earl Yes, but the point of putting javascript:void(0) is that it's supposed to do nothing. The onclick event is handled via jQuery in this example.
    – Kevin Pang
    Commented Apr 8, 2011 at 15:32

3 Answers 3

55

One big difference is that jQuery's events are handled in a registry which is parsed on the click event. Crucially, this means that you are permitted to assign multiple callbacks, and have them triggered in the order in which they were registered:

<script type="text/javascript">
    $(document).ready(function() {
        $("#clickme").click(function() {
            alert("clicked!");
        });
        $("#clickme").click(function() {
            alert("I concur, clicked!");
        });
    });
</script>

They will both be invoked on the click event, in that order. The "real" onClick event is overridden by jQuery's registry-driven system. In the vanilla document structure, without a system like jQuery in place, there can only be one onClick event.

1
  • 2
    +1. Nice answer. Event normalization (which I think jQuery does) is anther difference.
    – seth
    Commented Sep 11, 2009 at 0:08
8

It is also a cleaner separation of UI code (the HTML) and the logic code (the JavaScript). It makes reading each a bit easier.

6

One of the differences is that adding handlers with jQuery's click doesn't remove previous handlers.

Not the answer you're looking for? Browse other questions tagged or ask your own question.