Basic Javascript and Html

Started by
1 comment, last by Chris_F 12 years, 2 months ago
I'm trying to learn some web programming and just spent hours trying to get the most basic javascript working. I don't understand where I'm going wrong, I've downloaded similar examples to the code I wrote and they work fine but my own javascript does not work at all! I would really appreciate if someone could take the time to try to help me figure out what I'm doing wrong.

event.js
[source]
document.getElementById("width").onchange = checkDimensions;
[/source]

checkDim.js
[source]
function checkDimensions() {
document.getElementById("width").value = "HELLO";
return false;
}
[/source]

index.html
[source]
<?xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Canvas Printing Calculator</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="event.js">
</script>
</head>
<body>
<form action="">
<input type="text" id="width" size="30"/>
</form>
</body>
<script type="text/javascript" src="checkDim.js">
</script>
</html>
[/source]
Advertisement
The document, including the Javascript, is parsed and executed top-down. When your file event.js is loaded, it is executed, but at that point there is no element with id "width" yet. You need to execute that line after the element with id "width". You also need to ensure that the function checkDimension actually exists at the point that you are installing the onchange callback. At this point, the error is that checkDimension is an unknown symbol, because it will be loaded later into the document.

The way to do these things is to not execute the initialization code until the document has been entirely loaded. Install a callback function to the onload property of window or document, which will be called when the whole document (which includes the presence of the element with the "width" id, and the checkDimension function).

window.onload = function() {
document.getElementById("width").onchange = checkDimensions;
}

It creates an anonymous function and assigns it to the onload callback. When the document has finished loading, it is called so you can install the callback to the desired element.
Alternatively


document.addEventListener("DOMContentLoaded", function () {
document.getElementById("width").onchange = function() {
this.value = "HELLO";
return false;
}
}


The advantage of DOMContentLoaded is that it executes as soon as the DOM has loaded, where as window.onload will wait until all content has finished loading. If your page has images and ads, this means your code could get to execute much sooner.

This topic is closed to new replies.

Advertisement