How DHTML Works
As I mentioned earlier, DHTML is a combination of HTML, Cascading Style Sheets, JavaScript, and the Document Object Model. Example 29-1 illustrates how these elements work together. The web page shown here uses simple DHTML to change the style of links to be red and underlined when the mouse is rolled over them. You can use this basic format to tie CSS styles to common events like onMouseOver or OnClick, so you can change the styles of most elements on the fly.
Example 29-1. Rollover style changes using DHTML
<html> (A) <head>
<title>Rollover Style Changes</title>
<style> (B) <!-- a {
text-decoration: none;
}
-->
</style>
<script> (C) <!-- function turnOn(currentLink) {
currentLink.style.color = "#990000"; (D) currentLink.style.textDecoration = "underline";
}
function turnOff(currentLink) {
currentLink.style.color = "#0000FF"; currentLink.style.textDecoration = "none";
}
//-->
</script>
</head>
<body >
<a href="#home" (E) >Home</a>
<a href="#contact" >Contact</a>
<a href="#links" >Links</a>
</body>
</html>
- (A)
- This page is an HTML file, so it starts with normal
<html>and<head>HTML tags.
- (B)
- In the
<head>, we have a CSS style sheet, defined using the<style>tag, that removes any text decorations from all the links in the document. In this case, the point is to remove the default underlines from links.
- (C)
- Inside the
<script>tag, there are two JavaScript functions,turnOn( )andturnOff( ), that change the style of a link when the user moves the mouse over and back out of the link. When the mouse enter a link, the text is underlined and turned red. When the mouse exits, these effects are removed.
- (D)
- The script uses the DOM to reference the link's
styleattribute and change thecolorandtextDecorationproperties, which are the DOM equivalents of the CSS propertiescolorandtext-decoration.
- (E)
- In this
<a>tag, theonMouseOverandonMouseOutevent handlers are used to set up the calls toturnOn( )andturnOff( ).