Script works after form, but not before, why?

Hello,

I am reading some JS book and basically there is this code that inputs some text into a text box using getElementById, and i have that script as an external file, but if it is placed above the form, for example in the head section, it doesn’t work, but if it is placed after the form it works. Why is that ?

html form:


<body>
<a href="ssfsf.html" id="msg_link">Get Message</a>
<br /><br />
<form>
<input type="text" id="msg_box" />
</form>
<script language="javascript" src="functions.js"></script>
</body>

</body>

js code:


var message_text = 'Help! Im in a box!';
var message_link = document.getElementById("msg_link");
var message_box = document.getElementById("msg_box");


message_link.onmouseover = function() {
	
	message_box.value = message_text;
	
}

message_link.onmouseout = function() {
	
	message_box.value = '';
	
}

thanks!

This is because the browser parses and executes javascript as it finds it in the HTML. If the SCRIPT element is before the FORM, then the FORM doesn’t exist yet, so the script cannot operate on it.

You can instruct the browser to wait until the rest of the page has finished loading by wrapping your script in window.onload:

window.onload = function() {

var message_text = 'Help! Im in a box!';
var message_link = document.getElementById("msg_link");
var message_box = document.getElementById("msg_box");


message_link.onmouseover = function() {
	
	message_box.value = message_text;
	
}

message_link.onmouseout = function() {
	
	message_box.value = '';
	
}

}

But window.onload will also wait for images to download, so the recommended method is to put all your SCRIPT elements (you should have as few as possible to reduce the number of separate HTTP requests) just before the closing </body> tag.

Its because the way you have setup the script executes as it appears. So when executed in head section the elements are not there yet so getElementById returns null. But when the script appears after the form the elements are present and the script works. Ideally speaking scripts should be executed when the document is loaded.

Ooops 4 mins late :slight_smile:

Raffles, that did the trick, thank you very much.

Thank you both for your time.