faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

38 of 49 people (78%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How do I get the position of the mouse when an "onMouseOver" is activated?

May 15th, 2000 08:07
Mike Hall, Pete Ruby,


Both Netscape and IE provide an Event object that contains data for any 
given event. Netscape creates a new Event object for each event while IE 
has a single, global Event that can be referenced using 'window.event'.
Both browsers set the current mouse coordinates in the Event object, but 
naturally they use different property names. This example shows how you 
can retrieve those coordinates for either one.
<html>
<head>
<title></title>
<script language="JavaScript">
var isMinNS4 = (document.layers) ? 1 : 0;
var isMinIE4 = (document.all)    ? 1 : 0;
function myMouseOver(e) {
  var x, y;
  if (isMinNS4) {
    x = e.pageX;
    y = e.pageY;
  }
  if (isMinIE4) {
    x = window.event.x;
    y = window.event.y;
  }
  window.status = x + "," + y;
  return true;
}
</script>
</head>
<body>
<a href="myPage.html" 
   onmouseover="myMouseOver(event);">My Page</a>
</body>
</html>
Note that for NS, you need to pass 'event' explicity when setting the 
event handler in an HTML tag. This is not necessary in IE since there is 
only one, global Event object. Adding it won't cause an error in IE so 
this works nicely in either browser.