Blake Allen Blake Allen - 1 month ago 6
jQuery Question

onclick event does not run jQuery function

I have an html file which is correctly linked to a js file (and also the jquery library file).

<input type="button" onclick="practice();" id="intro_next_button" value="Practice"/>


Inside the js file:

$(window).load(function(){
function practice(){
alert("WORKS");
}
});


This runs if function practice is outside of the
$(window).load(function()
, but not when it is inside of it. There are many similar questions to this, but I have not found one that is specifically about an
onclick event
only not working inside of a jquery
$(window).load(function()
.

Answer

This doesn't work because anything defined (i.e. via keywords function or var) inside a function block applies that block as it's scope. So if you make a variable, x, inside the block you won't have the value outside there.

var x = 2;
function test() { var x = 5; }
console.log(x);

Prints 2.

These are also competing styles. Typically if you use window.onload or the "improved" jQuery $(document).ready you bind events in the body of the function.

$("#intro_next_button").click(function() { alert("WORKS"); });