12.4 Handling Mouse Events


In many previous examples, we've seen uses of the onClick event handler to initiate an action when a user clicks his mouse in a button or on a link. There are a number of other events that can be fired up because of some action of the mouse. When the user moves the mouse pointer over a link, image, or other object, the onMouseOver event handler is triggered, and when he moves the mouse pointer away from an object, the onMouseOut event is triggered. Table 12.4 lists events that are triggered when mouse movement is detected .

Table 12.4. Mouse events.

Event Handler

When It Is Triggered

onClick

When the mouse is clicked on a link and on form objects like button, submit

onDblClick

When the mouse is double-clicked on a link, document, form object, image

onMouseDown (NN6+)

When the mouse is pressed on a link, document

onMouseMove (NN6+)

When the mouse touches the link, form object

onMouseOut

When a mouse is moved out of a link, image map

onMouseOver

When a mouse is moved over a link, image map

onMouseUp

When the mouse is released from a link, document

12.4.1 How to Use Mouse Events

The onMouseOver and onMouseOut event handlers occur when the user's mouse pointer is moved over or out of an object. The onMouseMove event occurs when the mouse just touches the object. In the following example, every time the user touches the button labeled onMouseMove with his mouse, a function called counter() is invoked to keep track of the number of mouse moves that have taken place. That number is displayed in an alert dialog box, as shown in Figure 12.9. If the user double-clicks his mouse anywhere on the page, the a message will appear, and if OK is clicked, the window will be closed.

Example 12.8
 <html><head><title>Mouse Events</title> 1   <script language="JavaScript"> 2       var counter=0; 3  function alertme(){  alert("I'm outta hea!"); 4           window.close();         } 5  function track_Moves(){  6           counter++;             if(counter==1){                alert(counter + " mouse moves so far!");             }             else{                alert(counter + " mouse moves so far!");             }         }     </script>     </head> 7  <body bgColor="CCFF00" onDblClick="alertme()";>  <p><font face="arial" size=3>         Double click anywhere on this page to get out!     <p>         When the mouse moves over the link, an event is triggered. 8  <a href="#" onMouseOver="alert('Event: onMouseOver');">onMouseOver   </a><p>  When the mouse moves away from a link, an event is triggered. 9  <a href="#" onMouseOut="alert('Event: onMouseOut');">onMouseOut   </a><p>  When the mouse moves in or out of the button, a function<br>     is called that keeps track of how many times the mouse touched     the button. 10  <form>         <  input type="button"  value="onMouseMove" 11  onMouseMove="track_Moves();"  >     </form>     </body>     </html> 
Figure 12.9. Links and mouse events.

graphics/12fig09.jpg

EXPLANATION

  1. A JavaScript program starts here.

  2. A global variable called counter is initialized .

  3. If the user double-clicks his mouse anywhere on the page, an alert dialog box will appear; if he OKs it, the window will be closed.

  4. The window 's close method causes the current window to be closed.

  5. This function is called when the onMouseOver event handler is triggered. This event happens when the user touches his mouse on an object, in this case, a button object.

  6. The counter is incremented by one every time the user touches the button.

  7. The onDblClick event handler is an attribute of the HTML <body> tag. When the user double-clicks his mouse, the alertme() function will be called, and the window closed.

  8. The onMouseOver event handler is an attribute of the <a href> link tag. It is triggered anytime the user moves his mouse over the link. (The link has been deactivated by using the # sign.) When this event occurs, the alert method is called.

  9. The onMouseOut event handler is an attribute of the <a href> link tag. Any time the user moves his mouse away from this link, the event is triggered, and the alert method is called.

  10. The form starts here. The input type is a button.

  11. When the user's mouse touches the button, the onMouseMove event handler is triggered, and the track_Moves() function is called. This function will simply increment a counter by one, each time it is called, and then alert the user.

12.4.2 Mouse Events and Images ”Rollovers

The onMouseOver and onMouseOut event handlers are commonly used to create a rollover, an image that is replaced with a different image every time the mouse moves over a link or image. (See "A Simple Rollover with a Mouse Event" on page 336 in Chapter 11.) In the following example, if the user touches the first link, the picture of the first mouse will be replaced with a new picture, giving the illusion that the mouse's eyes are moving.

Example 12.9
 <html><title>Mouse Events</title>     </head>     <body bgColor="orange"> 1  <a href="#" onMouseOver="document.mouse.src='mouse.gif'">  onMouseOver </a><p> 2  <a href="#" onMouseOut="document.mouse.src='mouse2.gif';">  onMouseOut</a><p> 3   <img src="mousestart.gif" width=300 height=150 name="mouse">     </body>     </html> 

EXPLANATION

  1. The onMouseOver event handler is assigned to a deactivated link (# causes the link to be inactive). When the mouse rolls onto the link, the event is triggered, and a new image, called mouse.gif will replace the original image, mousestart.gif .

  2. The onMouseOut event handler is assigned to another deactivated link, this time with another image of the mouse. When the mouse rolls away from the link, the event is triggered, and a new image, called mouse2.gif will replace the last image, mouse.gif . By rolling the mouse back and forth, the mouse's eyes seem to move. The words " hi " and " bye " also keep changing.

  3. This is the original image that is displayed before the links are touched. See Figure 12.10.

    Figure 12.10. Original display (left), as the mouse moves over the link (middle), and as the mouse moves away from the link (right).

    graphics/12fig10.jpg

12.4.3 Creating a Slide Show

By using a timer with an event, you can do all sorts of fun things with images. You can create scrolling banners, rotating billboards, button rollovers, and more. The following example is a simple slide show. Four images are preloaded and each image is assigned to an array element. When the user moves his mouse onto one of the pictures, a new picture will replace the previous one every two seconds, and when he moves his mouse away from the image, the show stops. Any time the mouse moves over the image, the show starts again.

Example 12.10
 <html>     <head><title>The Four Seasons</title>     <script language="JavaScript"> 1  var season = new Array();  2       var indx = 0; 3       var timeDelay=2000; 4       if(document.images){ 5  season[0]=new Image();  6           season[0].src="winter.jpg";             season[1]=new Image();             season[1].src="summer.jpg";             season[2]=new Image();             season[2].src="fall.jpg";             season[3]=new Image();             season[3].src="spring.jpg";         } 7  function changeSeason()  { 8           var size= season.length - 1;             if( indx < size ) {                indx++;             }             else {                indx = 0;         } 9  document.times.src= season[indx].src;  10  timeout=setTimeout('changeSeason()', timeDelay);  } 11  function stopShow(){  12          clearTimeout(timeout);         }     </script>     </head>     <body bgcolor="cornflowerblue"><center><font face="arial">     <h2>The 4 Seasons</h2><b>     To see slide show, put your mouse on the image.<br>     Move your mouse away from the image, to stop it. 13  <a href="javascript:void(null);"   onMouseOver="return changeSeason();"   onMouseOut="return stopShow()">  14  <  img name="times"  src="winter.jpg" align="left"     border=8  hspace="10" width="700" height="200">     </a>     <br>     </body>     </html> 

EXPLANATION

  1. A new Array object, called season is declared. It will be used to store an array of images.

  2. A global variable called indx is declared and initialized to 0.

  3. The value 2000 is assigned to another global variable, called timeDelay .

  4. If this browser has an image object, then an array of objects is created with the Image() constructor.

  5. Using the Image() constructor preloads and caches the images. Each new image object is assigned to an element of the season array.

  6. The first element of the season array gets a new Image object. The src property (the location and name of the image) is winter.jpg , located in the present working directory.

  7. A user-defined function called changeSeason() is defined. It is called when the onMouseOver event handler is triggered by the user moving his mouse onto the image. Its purpose is to replace one image with another image in the season array, every 2 seconds, for as long as the user's mouse is on the image. (It might be nice to add a little Vivaldi audio clip here to enhance the show!)

  8. The size of the array is its length “ 1 since array indices start at 0. As long as the array size isn't surpassed, the index value will keep being incremented by 1.

  9. This is where image replacement happens. The name of the original image is times (line 14) and it is referenced by JavaScript using the DOM hierarchy: docment.times.src is assigned a new image from the season array, season[indx].src. The new image will be displayed.

  10. The window object's setTimeout() method will be set to call the changeSeason() function every 2,000 milliseconds (2 seconds). Every 2 seconds a new image is displayed as long as the user keeps his mouse on an image.

  11. The user-defined function called stopShow() is defined. It is called when the onMouseOut event is triggered by the mouse moving away from the image. It turns off the timer, stopping the slide show.

  12. The setTimeout() method is cleared.

  13. The link has two mouse event handlers, onMouseOver and onMouseOut . The pseudo URL, javascript:void(null) , deactivates the link and ensures that if there is a return value from the event, it will be nullified. Since neither of the events return anything, it would be enough to just use the protocol as javascript: . The display is shown in Figures 12.11 and 12.12.

    Figure 12.11. Watch the seasons change every 2 seconds.

    graphics/12fig11.jpg

    Figure 12.12. Spring image (top), summer image (middle), and fall image (bottom) are all part of the slide show created in Example 12.10.

    graphics/12fig12.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

Similar book on Amazon

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