From what I have read the preferred format for javascript is in a separate file that is included at the end of the header. I have written a simple screen that increments indx on a time interval and reverses if the Previous button is pressed. If I include the script at the end of the body it works fine, but if I include at the end of the header the buttons have no effect. Am I missing something here? Could someone explain please?
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}
var del = 5000; /* time delay in milli seconds */
var indx = 0;
var direct = 1;
var intervalID = window.setInterval(proceed, del);
function proceed() {
indx += direct;
if (indx <= 0){
indx = 0;
direct = direct * -1;
};
msg = 'indx = ' + indx + ' direct = ' + direct;
document.getElementById("msg").innerHTML = msg;
}
function test() {
alert('this is a test')
}
function handleButtonPress(e) {
if (e.target.id == "next") {
direct = 1;
}
else if (e.target.id == "prev") {
direct = -1
}
}
function displayMsg(msg) {
document.getElementById("msg").innerHTML = msg;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example Timeout + Buttons</title>
<!-- <script src="test.js"></script> Does not work here!! -->
</head>
<body>
<p id='msg'></p>
<p>
At start<br>
<button id="next">Next</button>
<button id="prev">Previous</button>
</p>
<!-- Script works here!! -->
<script src="test.js"></script>
</body>
</html>
` closing tag as possible. Your script fails when it's in the head because the DOM hasn't been built at the time it runs, so it can't find any `
– Pointy Dec 10 '15 at 22:49