Book HomeWeb Design in a NutshellSearch this book

29.2. 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 bgcolor="#FFFFFF">
<a href="#home"   (E)
   onMouseOver="turnOn(this);" onMouseOut="turnOff(this);">Home</a>
<a href="#contact" 
   onMouseOver="turnOn(this);" onMouseOut="turnOff(this);">Contact</a>
<a href="#links" 
   onMouseOver="turnOn(this);" onMouseOut="turnOff(this);">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( ) and turnOff( ), 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 style attribute and change the color and textDecoration properties, which are the DOM equivalents of the CSS properties color and text-decoration.

(E)

In this <a> tag, the onMouseOver and onMouseOut event handlers are used to set up the calls to turnOn( ) and turnOff( ).



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.