Free Javascript Tutorials

home

JavaScript Tutorials

The Document Object (Part Three)

 
Our quick javascript links
Little Programmes
 
 
 
 
 
 

 

A JavaScript Rollover

 

For this part, you may need these two images. Right click on the images, and save them to your own computer:

Now we can begin.

A useful property of document is images. The images property tells you if any images are loaded. If the answer is yes, and your HTML images have a NAME attribute, document.images can gain access to them. Why is this useful? Well, let's see. Examine this HTML code for an image:

<BODY>

<IMG SRC = "pointer1.jpg" NAME = "but1">

</BODY>

Simple enough, because it's just standard HTML Image code. We can turn the image into a link by surrounding it with an Anchor tag:

<BODY>


<A HREF = "page2.html">

<IMG SRC = "pointer1.jpg" NAME = "but1" Border = 0>

</A>

</BODY>

Still, simple enough: now we've just added the HREF tag and switched the borders off in the image. However, we can add a bit of JavaScript to the Anchor link. This bit of JavaScript uses the images property of document. Like this:

<BODY>

<A HREF = "page2.html" OnMouseOver = "document.images.but1.src= 'pointer2.jpg'">

<IMG SRC = "pointer1.jpg" NAME = "but1" Border = 0>

</A>

</BODY>

That code looks a bit messy spread over two lines. Notice, though, what was added to the HREF code. It was this:

OnMouseOver = "document.images.but1.src= 'pointer2.jpg'"

Remember the OnClick event of the button you did? Well, OnMouseOver is another event you can use. This event does something when the user places the mouse over a link, or an image, or whatever. After the equals sign (assignment operator, if you please), we write the code (not forgetting all those awfully messy double and single quotes):

"document.images.but1.src= 'pointer2.jpg'"

See what we're pointing at? The document.images part is pointing to our image that has the NAME but1. We're then saying access the SOURCE (src), and change it to 'pointer2.jpg'.

To see the effect that all this code has, move your mouse over the image below. Move it away and then back again.

Neat, hey? Are the neighbours impressed yet? Blimey, they're a tough crowd.

The code for the "dancing hand" uses an event related to the OnMouseOver event - the OnMouseOut event. The code is then exactly the same, except you're resetting the image back to pointer2:

OnMouseOut ="document.images.but1.src='pointer2.jpg'"

So by using the images property of document you can create a rollover effect. This is not, however, the recommended way to create a rollover. The standard way is to pre-load the images in the head section of the web page, then use something called a function to switch the images around.


Another property of document is forms. We're going to use the Form property of document to validate user input. For that, we need to delve a little deeper into the JavaScript, so we'll leave it till later.

<--Back to the JavaScript Contents Page