To teach you how to tweak JavaScript code so it works on your own Web page, let's take a look at a page that's using JavaScript to set the background color randomly each time a user hits Reload:
<html>
<head>
<script language="JavaScript">
<!-- hide from old browsers
function setBackgroundColor(color1, color2, color3, color4) {
theColors = new Array(color1, color2, color3, color4);
var whichColor = Math.round(Math.random()*1000) % 4;
document.bgColor = theColors[whichColor];
}
// stop hiding -->
</script>
</head>
<body onLoad="setBackgroundColor('#ff0000','#00ff00','#ffff00','#3333ff');">
<font face="Arial, Helvetica, sans-serif" size="4">
Hit Reload (or Refresh if you're using Internet Explorer)
to see a new background.
</font>
</body>
</html>
To see what this code will do, check out the actual page and hit Reload a few times. See all the pretty colors? Let's learn how it works.
There are several important things going on here. First of all, notice the <script> tags (highlighted in red above). These tags are used to separate JavaScript from the regular HTML code in your document. Everything in between <script> and </script> is interpreted as JavaScript. Old browsers from before the days of JavaScript should simply ignore everything inside the <script> tags, but in some cases, they try to display the code as text. For this reason, it's good form to comment out your JavaScript with an initial line that begins "<!--" and a final line that begins with "//" and ends with "-->".
These <script> blocks can appear anywhere in your document, but be aware that the JavaScript instructions within the <script> tags will be executed as they appear. For example, a command located in the <head> of a document will generally be executed before one located in the <body>.
Now that you know where you can put that JavaScript (anywhere), let's take a look at what's going on inside the script.
next page»