Mouse Rollovers


One of the main reasons JavaScript became popular was its capability to swap images in the browser in real time when the mouse moved over an image. Here's an example that shows how that works, using the mouse-over and mouse events. You can handle these events in the <IMG> element itself, or in an element that encloses the <IMG> element. For example, here I'm enclosing an image in a hyperlink <A> element. Note that I've set the BORDER property of the <IMG> element to "0" so that no hyperlink border appears. When the page loads, the image displayed shows the text Image 1 , but when the mouse moves over the image, it's swapped for an image that displays the text Image 2 :

(Listing 15-07.html on the web site)
 <HTML>      <HEAD>          <TITLE>Mouse Rollovers</TITLE>          <SCRIPT LANGUAGE= JavaScript>              <!--  function ImgOver()   {   document.form1.img1.src="image2.jpg"   }   function ImgOut()   {   document.form1.img1.src="image1.jpg"   }  //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>Mouse Rollovers</H1>          <FORM NAME="form1">  <A HREF="http://www.w3.org" NAME="link1"   ONMOUSEOVER="ImgOver()" ONMOUSEOUT="ImgOut()">   <IMG BORDER="0" NAME="img1" SRC="image1.jpg" WIDTH="216" HEIGHT="72">   </A>  </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 15.8. Handling mouse rollovers by swapping images such as this is one of the favorite aspects of JavaScript for many programmers. We'll also take a look at handling mouse rollovers for text in Chapter 21, "Cascading Style Sheets and CGI Programming."

Figure 15.8. Handling mouse rollovers.

graphics/15fig08.gif

Note that when you swap images such as this quickly, it's a good idea to have the new image already downloaded and in memory. You can do that by precaching the image.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

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