HomeDHTML Page 2 - Rough Guide To The DOM (part 2)
Making The Swap() - DHTML
Now that you know the theory behind the new DOM, it's time totake off the gloves and get your hands dirty. In this article, find out howthe new rules apply to old favourites like image swaps, form validation andframe navigation, and then learn how to use ordinary JavaScript to add andremove elements from the document tree on the fly.
The first item on the agenda today is an illustration of how you can use the DOM to accomplish one of the most popular dHTML applications - the image swap. Take a gander at the following HTML document:
Now, I've set this up so that "mouseover" and "mouseout"
events on the image are handled by the JavaScript function imageSwap(). This function is responsible for swapping the image each time an event occurs - so let's take a look at it.
<script language="JavaScript">
var normal = "logo_n.gif";
var hover = "logo_h.gif";
function imageSwap()
{
var imageObj = document.getElementById("logo");
var imageSrc = imageObj.getAttribute("src");
if (imageSrc == normal)
{
imageObj.setAttribute("src", hover);
}
else
{
imageObj.setAttribute("src", normal);
}
}
</script>
If you remember what I taught you last time, none of this
should come as a surprise. I've first defined the "normal" and "hover" state images, and then created a function called imageSwap(), which is called whenever the mouse moves over and out of the image.
The imageSwap() function obtains a reference to the image via its ID, and then obtains the current value of the image's "src" attribute. It then checks the value against the values of the "normal" and "hover" variables, and changes the image source appropriately.
This article copyright Melonfire 2001. All rights reserved.