Cristian Crishk Cristian Crishk - 3 months ago 11
Javascript Question

Why am I getting a ReferenceError for a function defined in $(document).ready() used in an HTML onclick handler

I have the following code:

index.html:

<!doctype html>
<html>
<header>
<script src="js/jquery-2.2.1.min.js"></script>
<script src="js/script.js"></script>
<script src="js/validator.js"></script>
</header>
<body>
<form novalidate>
<input type="button" value="Validar" onclick="callMe();"/>
</form>
</body>
</html>


script.js:

$(document).ready( function() {
function hello()
{
alert( "Hello world!" );
}
});


validator.js:

$(document).ready( function() {
function callMe()
{
hello();
}
});


When I view the index.html file, I get the error:

index.html:10 Uncaught ReferenceError: callMe is not defined


Simply that's the question; I don't understand why. The function is defined and is included before, and called after, all includes.

Now, I can see that if I define the event click with
.on
in validator.js, using jQuery to call the function 'callMe', it is present and works. But, I get a new error:

Code:

$('input').on( "click", function() {
callMe();
});


Error:

index.html:10 Uncaught ReferenceError: hello is not defined


Now
hello
is not defined :(.

Answer

callMe is not defined in the global scope (the scope in which the HTML code is looking for it). All of the <script> files are added, initially, within the global scope. Putting the definition of hello() and callMe() each within an expression, $(document).ready(//in here), and then within another function limits their scope to within that function. That function only has the scope of that expression.

You would need:

Script:

function hello()
{
    alert( "Hello world!" );
}

$(document).ready( function() {
    hello();
});

Validator:

function callMe()
{
    hello();
}
Comments