Coders' Corner Search:
General :: Web publishing :: JavaScript :: Events
Questions, answers and code examples dealing with javascript event handlers.

Articles:


Featured Article

Catch mouse move events in Internet Explorer and Netscape

Question:

How can I catch mouse move events both in Internet Explorer and Netscape? I need to keep track of the current position (in pixel coordinates) of the mouse on the document.

Answer:

You need to see if IE or Netscape is running by checking for document.all or document.layers. Note that the code to access the event coordinates for Netscape 6 is different than for Netscae 4 and 5. Even the event handler registration is different for each browser.

The example works for Netscape 4,5,6 and IE 4,5,6.

<SCRIPT LANGUAGE="JavaScript1.2">
 function mouseMoveHandler (evt) {
   var x = document.all ? event.clientX : document.layers ? evt.x : evt.clientX;
   var y = document.all ? event.clientY : document.layers ? evt.y : evt.clientY;
   window.status = x + ':' + y;
 }
 if (document.layers)
   document.captureEvents(Event.MOUSEMOVE);
 if (document.layers || document.all)
   document.onmousemove = mouseMoveHandler;
 if (document.addEventListener)
   document.addEventListener('mousemove', mouseMoveHandler, true);
 </SCRIPT>