Cristian Crishk Cristian Crishk - 3 months ago 9
HTML Question

Whay I'm getting ReferenceError in javascript?

I have the following code:

HTML index:

<!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

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


Validator

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


When I execute the index.html 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 the validator.js using jquery to call the function 'callMe', it is present and works but I get a new error:

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


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