How to Detect the Position of the Mouse Cursor in javascript

Home arrow HTML & CSS Tutorials arrow Javascript arrow How to Detect the Position of the Mouse Cursor in javascript
How to Detect the Position of the Mouse Cursor in javascript Print E-mail
Contributed by Teddy   
Tuesday, 26 September 2006

When need to know Position of the Mouse Cursor

When doing with some mouse events, such as mouseover or mousemove, we need to use the coordinates of the mouse cursor

Solution of this problem

The event object contains informtion of the position of the cursor.The standard method of obtaining the mouse cursor’s position relative to the entire page is via the pageX and pageY properties of the event object. 

But to IE, we need use clientX and clientY, though they measure the distance from the mouse cursor to the edges of the browser window. In order to find the position of the cursor relative to the entire page,

Sample code:

function displayMouseCursorPosition(event)
{
if (typeof event == "undefined")
{
event = window.event;
}
var scrollingPosition = getScrollingPosition();
var cursorPosition = [0, 0];
if (typeof event.pageX != "undefined" &&typeof event.x != "undefined")
{
cursorPosition[0] = event.pageX;
cursorPosition[1] = event.pageY;
}
else
{
cursorPosition[0] = event.clientX + scrollingPosition[0];
cursorPosition[1] = event.clientY + scrollingPosition[1];
}
var paragraph = document.getElementsByTagName("p")[0];
paragraph.replaceChild(document.createTextNode("Your mouse is currently located at: " + cursorPosition[0] +"," + cursorPosition[1]),paragraph.firstChild);
return true;
}

clientX/clientY are valid W3C DOM event properties that exist in most browsers, if we want to know the cursor position  in firefox, just need below code

function getcursorPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    return cursor;
}

Related articles:

JavaScript Array

Last Updated ( Tuesday, 26 September 2006 )

  home              contact us

 

©2006-2009 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground