Marius-Cristian Dragan Marius-Cristian Dragan - 6 months ago 14
jQuery Question

JavaScript and jQuery function calls

My html has jquery loaded:

<script src=""></script>

Then, before ending body I load my custom file:

<script type="text/javascript" src="checkSum.js"></script>

My .js file looks like this:

$(document).ready(function () {
//$('#sum').onclick(function(event){alert("onclick inside");}); //not norking

//$( '#sum' ).on( 'click', function (event) { alert("on inside"); }); //working

//function baubau(){alert("baubau inside")} //not working


//$('#sum').onclick(function(event){alert("onclick outside");}); //not norking

//$( '#sum' ).on( 'click', function (event) { alert("on outside"); }); //works

//function baubau(){alert("baubau outside")} //not working

$(document).on('click', '#sum', function() { alert("hello"); }); //works

After each line you can see the comment if the function gets called or not. Could anyone please help me understand the differences and also suggest me a good site to learn javascript and jQuery? I'm a Java developer but when it comes to javascript and jQuery, I've never ever understood anything :))


With where you've put your script tag, there's no need to use $(document).ready. The only time you need to use that is when you don't control where your script tags go. If you do, and you put it at the end of the body as you've done, there's no need.

$('#sum').onclick(function(event){alert("onclick inside");}); //not norking

jQuery has no onclick method. Raw DOM elements do, but not jQuery instances (which are wrappers around sets of DOM elements [usually]).

$( '#sum' ).on( 'click', function (event) { alert("on inside"); }); //working

That's how you set up a direct click handler on an element with jQuery when looking it up by ID.

function baubau(){alert("baubau inside")} //not working

That declares a function, but doesn't call it. Unless something calls it, you won't see the alert.

$('#sum').onclick(function(event){alert("onclick outside");}); //not norking

See above.

$( '#sum' ).on( 'click', function (event) { alert("on outside"); }); //works

Because you don't need ready if you put your script at the end.

function baubau(){alert("baubau outside")} //not working

See above.

$(document).on('click', '#sum', function() { alert("hello"); }); //works

Hooks up a click handler on document, but only fires that handler if the event passes through an element matching the '#sum' selector you've provided. It's called event delegation. Very handy for setting up handlers for dynamically-added and -removed elements.

More in the jQuery documentation.