Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using jQuery's onclick and the onclick attribute?

Tags:

jquery

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>
like image 729
Kevin Pang Avatar asked Dec 29 '08 21:12

Kevin Pang


People also ask

What is difference between Onclick and Onclick?

onClick will work in html, but if you're defining the handler in JS, you need to use the lowercased onclick. in XHTML, HTML attributes are case sensitive.

What is an onclick attribute?

The onClick attribute is an event handler that instructs the browser to run a script when the visitor clicks a button.

What is the difference between click and Onclick in angular?

The difference is that the first ( click ) is an event listener, and the second ( onclick ) is an event handler content attribute.

What is the difference between .click and .on (' click in jQuery?

. click events only work when element gets rendered and are only attached to elements loaded when the DOM is ready. . on events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).


3 Answers

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.

like image 50
Adam Bellaire Avatar answered Oct 03 '22 13:10

Adam Bellaire


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

like image 32
palehorse Avatar answered Oct 03 '22 13:10

palehorse


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

like image 41
orip Avatar answered Oct 03 '22 11:10

orip