Monday, April 11, 2011

Get X-Y coordinates relative to div on mouse click cross browser

Following is the function to get the X-Y coordinates of mouse click relative to div which works across browsers:

function getPos(obj,e){
var evtobj=window.event? event : e;

if (Browser == 'Explorer' || Browser == 'Opera')
clickX = evtobj.offsetX;
clickY = evtobj.offsetY;
clickX = evtobj.layerX;
clickY = evtobj.layerY;
alert('clickX:'+clickX+', clickY'+clickY);

HTML will look like this:
<div style="width:400px;height:500px;border:1px solid red;position:relative;" onclick="getDetails(this,event)">

Only thing notable in the HTML is that we need to declare the 'position' explicitly.

No comments:

Post a Comment