Reputation: 41357
Could this cause potential problems:
<HTML> <BODY> ... <INPUT name="xyz" onchange="myFunction();"> ... <SCRIPT> function myFunction() { ... } </SCRIPT> </BODY> </HTML>
What happens if the page loads slowly and the form renders before the script portion at the bottom is loaded? Will a JavaScript error occur if the user enters some text into the INPUT box?
Upvotes: 2
Views: 312
Reputation: 490243
It works, though it may be a problem if you loaded more HTML and it took longer for the browser to parse your JavaScript at the end. In that case, your function won't be defined and you will get...
myFunction() is not defined
Note you need to add open and closing parenthesis ((
& )
) after myFunction
.
Whilst functions declarations are hoisted, they are only hoisted in their containing script block.
Also, you should really use lowercase tags, it isn't 1998 anymore :) And a doctype also helps, and finally, you should try and remove your event handlers from inline attributes.
Upvotes: 1
Reputation: 331
JavaScript development has changed over the years.
Not only is your original question being debated, but to go back to the theme of your original question, so is your methodology itself.
I highly recommend reading this short bit on some JavaScript best practices: http://www.catswhocode.com/blog/best-practices-for-modern-javascript-development.
Upvotes: 1
Reputation: 4475
You need to load the script before you can call it. Why don't you change it to something like this:
<input name="xyz" id="myInput">
...
<script>
function myFunction
{
...
}
window.onload = function() {
var myInput = document.getElementById('myInput');
myInput.onchange = myFunction;
}
</script>
This approach allows you to separate your markup and scripting and have all of your js in one place.
Upvotes: 3
Reputation: 30882
The script needs to be defined in the DOM prior to it being executed. If script is at the bottom it needs to be loaded prior to use.
Upvotes: 0