Creating Mouseover Buttons


<img src="/books/3/490/1/html/2/inactive.gif"   onmouseover="this.src='/books/3/490/1/html/2/active.gif';"   onmouseover="this.src='/books/3/490/1/html/2/inactive.gif';" /> 

One of the oldest effects in the World Wide Web consists of graphics that change their appearance when the mouse moves (hovers) over them. This is also called a "hover effect" or a "hover button"/"hover graphic." The name, by the way, is also reflected in the nonstandard hover pseudo CSS class some browsers support.

To change a graphic, you have to access it and then change its src property. Browsers support several methods of accessing graphics. The following ones work consistently across modern browsers:

  • Set the image's name attribute, and access it via document.images["name"].

  • Set the image's name attribute, and access it via document.images.name (however, then some special characters like blanks or dashes are not possible in the name attribute).

  • Access the image using its position on the page, via the document.images array: document.images[0] for the first image, document.images[1] for the second image, and so forth.

  • Set the image's id attribute, and access it via document.getElementById("id").

The appropriate event for the mouse moving over the image is mouseover, and when mouseout occurs, you should reset the image to its original state. The preceding code does this and puts everything in the <img> element, but you could also use a generic custom JavaScript function for doing so. The following code creates a function that expects the image's name and its URL in a function and then calls this using onmouseover/onmouseout:

A Hover Button (hover.html)

<script language="JavaScript"   type="text/javascript"> function changeImage(name, url) {   if (document.images[name]) {     document.images[name].src = url;   } } </script> <img   name="myImage"   src="/books/3/490/1/html/2/inactive.gif"   onmouseover="changeImage('myImage','active.gif');"   onmouseout="changeImage('myImage','inactive.gif');" /> 

Figure 3.1 shows two buttons; the mouse pointer is over the one on the right, demonstrating both states of the button.

Figure 3.1. The buttons change their appearance when the mouse hovers over them.


Warning

Older browsers (including Netscape 4.x) do not support onmouseover/onmouseout for anything other than links. In that case, you have to embed the image within an HTML link and use onmouseover/onmouseout in the <a> tag:

<a   href="#"   onmouseover="..." onmouseout="">   <img src="/books/3/490/1/html/2/..." /> </a> 






JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net