Using Mouse Events


document.onmousemove = showPosition; 

When the mouse is being used, there is one quite interesting event to listen to (apart from click, of course): mousemove. The mouse position can be determined by looking at certain properties. Again, these properties depend on which of the two browser groups the client belongs to: Internet Explorer or the rest of the world:

  • clientX and clientY for Internet Explorer

  • pageX and pageY for all other browsers

Here is a complete listing that shows the current mouse position in the status bar of the browser (if available):

Tracking Mouse Movements (mouse.html)

<script language="JavaScript"   type="text/javascript"> function showPosition(e) {   var x, y;   if (window.event) {     x = window.event.clientX;     y = window.event.clientY;   } else {     x = e.pageX;     y = e.pageY;   }   window.status = "x: " + x + ", y: " + y; } window.onload = function() {   document.onmousemove = showPosition; } </script> 

Warning

Some browsers do not allow JavaScript to update the status bar, for instance, recent Firefox versions. You do not get an error message, but the status bar remains unchanged. Figure 6.4 shows the result in a browser that does support changing the text in the status bar.

Figure 6.4. The mouse position is continuously updated.



Distinguishing Mouse Buttons

When it comes to finding out which mouse button has been pressed (when you listen to the click event), the browsers once again have different solutions. Both solutions use the button property of the event property, but the values are different.

Mozilla follows the W3C standard: 0 means left button, 1 means middle button, 2 means right button. However, the rest of the world, which includes Microsoft and other browsers, supports a more logical way: 1 means left button, 2 means right button, and 4 means middle button. As you can see from these numbers, these are all powers of 2. Therefore, you can combine these values. For instance, a value of 3 means that both the left and the right button have been pressed at the same time.





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