Blake Allen Blake Allen - 13 days ago 4x
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:

function practice(){

This runs if function practice is outside of the
, 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


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; }

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"); });