Mouse Event Handling


Many of the user 's interactions with your pages come in the form of mouse movements or mouse clicks. JavaScript provides a robust set of handlers for these events.

The onmousedown event

One of the questions most frequently asked by new JavaScripters is, "How do I hide my scripts from anyone coming to my page?" The answer is, simply, you can't. If anyone is determined enough, they can always find out what's in your code.

If you really need to try to hide your code from average surfers, though, Script 9.9 keeps them from viewing the page source via a mouse-click that would normally bring up the shortcut menu.

Script 9.9. This script will deter some inexperienced users from bringing up the shortcut menu on your pages.
  if (typeof document.oncontextmenu == "object") {   if (document.all) {   document.onmousedown = captureMousedown;  }  else {   document.oncontextmenu = captureMousedown;  } }  else {   window.oncontextmenu = captureMousedown;  }  function captureMousedown(evt) {   var mouseClick = (evt) ? evt.which : window.event.button;   if (mouseClick==1  mouseClick==2  mouseClick==3) {   alert("Menu Disabled");   return false;   }  } 

1.
 if (typeof document.oncontextmenu == "object") {   if (document.all) {      document.onmousedown = captureMousedown; 



This first block checks to see if this browser is Firefox, which uses window.oncontextmenu (and so doesn't know about document.oncontextmenu ). If it isn't Firefox, we next look for document.all , which is an easy way of checking to see if the browser is IE. If it is, we want to set captureMousedown() to run whenever onmousedown is triggered.

2.
 else {   document.oncontextmenu = captureMousedown; 



If we're here, it's because your visitor's got Safari, and that browser needs oncontextmenu set on the document object.

3.
 else {   window.oncontextmenu = captureMousedown; 



And finally, if the browser is Firefox, we want oncontextmenu events for the window to call the captureMousedown() function.

4.
 function captureMousedown(evt) { 



The function that handles the onmousedown and oncontextmenu events begins here. Netscape-based browsers and Safari generate the evt parameter being passed in automatically whenever an event is triggered, and this variable contains information about the event.

5.
 var mouseClick = (evt) ? evt.which : window.event.button; 



If the evt variable exists, we can determine which button the user clicked by checking evt.which . If the user has IE, the results of the user's action will be found in window.event.button . Either way, store the result in the mouseClick variable.

6.
 if (mouseClick==1  mouseClick==2  mouseClick==3) {   alert("Menu Disabled");   return false; } 



If mouseClick is 1, 2, or 3, put up an alert ( Figure 9.4 ) saying that that functionality is disabled, and return false. Returning false keeps the menu window from being displayed.

Figure 9.4. This alert box scares off the timid (and annoys the rest).


Tips

  • Why are we checking for three different mouse clicks? Shouldn't one be enough? In theory, yes, but in practice, noas shown in Table 9.1 . Unfortunately, this approach can backfire: you may successfully block left-click and right-click input (to block people from dragging images off Web pages, for example), but it also means that you might be keeping people from clicking any links on your page.

    Table 9.1. Mouse Click Codes

    Code

    Browser/Event

    1

    Internet Explorer/Left-click

     

    All Mac browsers/Control-left-click

    2

    Internet Explorer/Right-click

    3

    Firefox/Right-click

     

    All Mac browsers/Right-click


  • It's very simple for savvy surfers to work around this: all they have to do is turn JavaScript off in their browser, and their clicking ability returns. Putting your JavaScript code into an external .js file seems like a tricky workaround, but users can look in their cache folder on their hard disk. Or they can look at the source of your page, find the name of the external file, and then enter the URL of the external file in their browser, which obediently displays the file's contents. If you really worry about your source code being stolen, the only method that's guaranteed to keep it from being looked at is to never put it on the Web.

  • IE understands document.oncontextmenu , so you'd think that setting it would cause it to handle those eventsbut it doesn't. IE is the only browser that needs document.onmousedown to be set. And if you set both window.oncontextmenu and document.onmousedown , Firefox triggers every event twice, once for each action.


The onmouseup event

Similar to the onmousedown event, the onmouseup event is triggered when the user clicks the mouse and then releases the button.

The onmousemove event

The onmousemove event is triggered whenever a visitor to your page moves their mouse. In this example, the user gets the feeling that someone's watching their every move ( Figure 9.5 ). Scripts 9.10 , 9.11 , and 9.12 show how to use JavaScript to display eyeballs that follow your visitor around.

Figure 9.5. The eyeballs will follow the cursor, no matter where it goes.


Script 9.10. The HTML for the following-eyes example.
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>      <title>Mouse Movements</title>      <script language="Javascript"  type="text/javascript" src="script06.js">      </script>      <link rel="stylesheet" href="script06.css" /> </head> <body>      <img src="images/circle.gif" alt="left eye"  width="24" height="25" id="lEye" />      <img src="images/circle.gif" alt="right eye"  width="24" height="25" id="rEye" />      <img src="images/lilRed.gif"  alt="left eyeball" width="4" height="4"  id="lDot" />      <img src="images/lilRed.gif"  alt="right eyeball" width="4" height="4"  id="rDot" /> </body> </html> 

Script 9.11. The CSS for the following eyes example.
 body {      background-color: #FFF; } #lEye, #rEye {      position: absolute;      top: 100px; } #lDot, #rDot {      position: absolute;      top: 113px; } #lEye {      left: 100px; } #rEye {      left: 150px; } #lDot {      left: 118px; } #rDot {      left: 153px; } 

Script 9.12. Keep an eye (OK, two eyes) on your users with this script.
  document.onmousemove = moveHandler;   function moveHandler(evt) {   if (!evt) {   evt = window.event;   }   animateEyes(evt.clientX,evt.clientY);   }   function animateEyes(xPos,yPos) {   var rightEye = document.getElementById ("rEye");   var leftEye = document.getElementById ("lEye");   var rightEyeball = document.getElementById ("rDot").style;   var leftEyeball = document.getElementById ("lDot").style;   leftEyeball.left = newEyeballPos (xPos,leftEye.offsetLeft);   leftEyeball.top = newEyeballPos (yPos,leftEye.offsetTop);   rightEyeball.left = newEyeballPos (xPos,rightEye.offsetLeft);   rightEyeball.top = newEyeballPos (yPos,rightEye.offsetTop);   function newEyeballPos(currPos,eyePos) {   return Math.min(Math.max (currPos,eyePos+3),eyePos+17) + "px";   }  } 

1.
 document.onmousemove = moveHandler; 



For all browsers, if a mousemove event is triggered, call the moveHandler() function.

2.
 function moveHandler(evt) {   if (!evt) {     evt = window.event;   }   animateEyes(evt.clientX,evt. clientY); } 



The moveHandler() function will be triggered whenever a mousemove event occurs. If the visitor has Internet Explorer, we need to initialize evt , and then for all browsers, we call the animateEyes() function and pass it the X and Y cursor coordinates.

3.
 function animateEyes(xPos,yPos) { 



Here's where the actual eyeball movement is done, based on the X and Y coordinates passed in.

4.
 var rightEye = document.getElementById("rEye"); var leftEye = document.getElementById("lEye"); var rightEyeball = document.getElementById("rDot").style; var leftEyeball = document.getElementById("lDot").style; 



This section assigns variables that match up with the id s of the images of the circles of the eyeballs and the dots of the eyeballs.

5.
 leftEyeball.left = newEyeballPos (xPos,leftEye.offsetLeft); leftEyeball.top = newEyeballPos (yPos,leftEye.offsetTop); rightEyeball.left = newEyeballPos (xPos,rightEye.offsetLeft); rightEyeball.top = newEyeballPos (yPos,rightEye.offsetTop); 



This block draws the eyeballs based on the mouse pointer's position, using the results of the newEyeballPos() function defined in the next step.

6.
 function newEyeballPos (currPos,eyePos) {   return Math.min(Math.max(currPos, eyePos+3), eyePos+17) + "px"; } 



We never want the eyeball to go outside the eye, do we? So, for each eyeball, we check to make sure that it gets as close to the cursor as possible, while still appearing within the circle of the eye.

Tips

  • There's a common JavaScript widget on the Web where the page has a bunch of dots (or whatever the designer wanted) follow the cursor around the page. We didn't want to re-create an already existing effect, so we did the eyeballs instead; but if you want to put tag-along dots on your page, you should be able to just tweak this script.

  • Netscape 6 had a bug where both eyeballs were always placed 10 pixels too low. This bug was fixed in Netscape 7.


The onmouseover event

By now, you should be familiar with this event: it's our good buddy from image rollovers. This event will be triggered whenever the mouse is moved into any area for which the onmouseover has been registered.

The onmouseout event

And unsurprisingly by now, where there's an onmouseover , there's usually an onmouseout . This is triggered when the user moves the mouse out of an area for which the event has been registered.

The ondblclick event

One of the drawbacks of the Web is that user interface elements that computer users learned how to interact with have all changed on the Web. For instance, one of the first things that new computer users learn how to do is double-click with the mouse, but there's no double-clicking on the Web. Or at least, there hasn't been, but now with Scripts 9.13 and 9.14 , you'll be able to check for double mouse clicks.

Script 9.13. This HTML helps you work with double clicks.
[View full width]
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>      <title>Image Popup</title>      <script language="Javascript"  type="text/javascript" src="script07.js">      </script> </head> <body bgcolor="#FFFFFF"> <h3>Double-click on an image to see the full-size version</h3>      <img src="images/Img0_thumb.jpg"  width="160" height="120" hspace="10"  border="3"  alt="Thumbnail 0" id="Img0" />      <img src="images/Img1_thumb.jpg"  width="160" height="120" hspace="10"  border="3"  alt="Thumbnail 1" id="Img1" />      <img src="images/Img2_thumb.jpg"  width="160" height="120" hspace="10"  border="3"  alt="Thumbnail 2" id="Img2" /> </body> </html> 

Script 9.14. Capture and handle double clicks with this script.
 window.onload = initImages; function initImages() {      for (var i=0; i<document.images.length; i++) {  document.images[i].ondblclick = newWindow;  } } function newWindow() {      var imgName = "images/" + this.id + ".jpg"      var imgWindow = window.open(imgName, "imgWin", "width=320,height=240, scrollbars=no") } 

  • document.images[i].ondblclick = newWindow;

    The newWindow() event handler gets triggered when a user double-clicks one of the thumbnail images. In that case, a new window pops up ( Figure 9.6 ), showing the same image in a larger format.

    Figure 9.6. A double-click on a thumbnail opens the larger version of the image.

The onclick event

The onclick handler works in a similar fashion to the ondblclick handler, except that a single click triggers it instead of a double click. The onmouseup handler is also similar, except that the onclick requires that the user press the mouse button both down and up in order to be triggered, while the onmouseup requires just the latter.




JavaScript and Ajax for the Web(c) Visual QuickStart Guide
JavaScript and Ajax for the Web, Sixth Edition
ISBN: 0321430328
EAN: 2147483647
Year: 2006
Pages: 203

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