This section provides a quick description of how Web browsers execute JavaScript codes, provide DOM API for document interaction, and provide events to trigger JavaScript code execution.
A typical Web browser will provide support to JavaScript in 4 areas:
Support <script> tags in the HTML document to execute JavaScript codes while rendering the HTML document.
Support DOM (Document Object Model) API (Application Programming Interface) to allow JavaScript codes
to interact with the browser and the HTML document.
Support events to trigger executions of JavaScript codes while user interacts with the browser.
Support "javascript:" pseudo-URL - evaluating JavaScript code in the address field of the browser.
Let's use a simple JavsScript example to illustrate those areas:
<html>
<!-- DOM_and_Event.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>DOM and Event</title>
<script type="text/javascript">
var colorID = 0;
function changeColor() {
if (colorID == 0 )
document.body.bgColor = "lightgrey";
else if (colorID == 1 )
document.body.bgColor = "lightblue";
else if (colorID == 2 )
document.body.bgColor = "lightgreen";
else if (colorID == 3 )
document.body.bgColor = "lightyellow";
colorID = (colorID+1)%4;
}
</script>
</head>
<body>
<p>
<script type="text/javascript">
document.write('Hello World!');
</script>
</p>
<form>
<input type="button" value="Click to change background color"
onClick="changeColor();"/>
</form>
<p>Want to know the color code?
<a href="javascript:alert(document.body.bgColor)">Click here.</a>
</p>
</body>
</html>
Run this JavaScript example in a Web browser, and click the change color button.
The browser will change the background color of the page each time you click the button.
If you want to know the code value of the current background color, you can click
the hyper link near the end of the page.
Now look at the JavaScript example again. The browser indeed supports you in 4 areas:
1. Executes the JavaScript code included in the "script" tag while rendering the HTML document: