Inside register.js I have a function called username() and I want to call it from my webpage but the function will not run.
Here is where I include the .js file and call the function:
<head>
<link rel="stylesheet" href="css/base.css" />
<script src="resources/jquery-1.8.1.min.js"></script>
<script src="resources/register.js"></script>
<script type="text/javascript">username();</script>
</head>
This is in the .js file:
function username(){
document.getElementById("username").innerHTML="Username already in use";
}
This is a common mistake from folks just starting out in Javascript. Trouble is, if you don’t know what to call it, it is hard to search for the answer.
What is happening: When the
<head>element is processed, nothing in the document body exists yet. Your elementusernamedoesn’t exist, so thegetElementByIdfails.Solution 1 Move
<script type="text/javascript">username();</script>to just before the</body>so everything will be in place.Solution 2 Use the
onloadevent to run your Javscript after everything else runs with a(jQuery has its own
onloadevent handling as well.)