1

Say I have two buttons, like this:

<input type="button" id="button1" value="click me 1" />
<input type="button" id="button2" value="click me 2" />

What would be the difference, besides the code is different, of putting an onclick attribute on one of them, and using jQuery to handle the other?

HTML:

<input type="button" id="button1" value="click me 1" onclick="alert('Clicked button 1!');"/>
<input type="button" id="button2" value="click me 2" />

JS/jQuery:

$(document).ready(function() {
    $("#button2").click(function(){
        alert("Clicked button 2!");
    }); 
});
Community
  • 1
  • 1
Mingle Li
  • 1,311
  • 1
  • 13
  • 34
  • _"What would be the difference, besides the code is different, of putting an onclick attribute on one of them, and using jQuery to handle the other?"_ First button does not require jQuery to return results – guest271314 Sep 06 '15 at 15:58
  • @guest271314 duh, did you see **besides the code is different**? – Mingle Li Sep 06 '15 at 16:03

3 Answers3

2

Well the effect is the same. Yet there are some differences like: While the first event is triggerd when clicking the first button, the content is being loaded after the page load , the second one is being triggered , of course after clicking , yet the content is being initialised every moment.

Reznicencu Bogdan
  • 910
  • 1
  • 11
  • 23
1

Essentially, there is no difference in the functionality of the two controls - they will both execute the same command.

However, if structured correctly, your site should load any external scripts (such as with the second example) for the page last to reduce loading times.

Basically, although the difference will be unnoticeable with a small-scale webpage, the first example will cause the function call to be loaded while the page is being generated, whereas the second should be loaded after the page has finished loading - meaning slightly less time to load the actual page.

EDIT:

However, upon further research, it seems modern browsers are more capable of handling this process, see: Where should I put <script> tags in HTML markup?

Community
  • 1
  • 1
Callan Heard
  • 707
  • 8
  • 18
1

They accomplish the same thing, but there are some differences:

  • The event binding in HTML exists when the element is created, while the event bound with jQuery is added somewhat later, when the document has completed loading and the ready event is triggered.

  • jQuery events are multicast, i.e. you can bind multiple events of the same kind to the same element.

Guffa
  • 640,220
  • 96
  • 678
  • 956