OffsetX and OffsetY in Firefox

offsetX and offsetY are used to get the position relative to an element of a mouse event. This works in Chrome and a few other browsers, but not in firefox. At times you will need these values, especially when making canvas games. Here’s a little function to calculate the offset for you:


function getOffset(evt)
{
if(evt.offsetX!=undefined)
return {x:evt.offsetX,y:evt.offsetY};

var el = evt.target;
var offset = {x:0,y:0};

while(el.offsetParent)
{
offset.x+=el.offsetLeft;
offset.y+=el.offsetTop;
el = el.offsetParent;
}

offset.x = evt.pageX - offset.x;
offset.y = evt.pageY - offset.y;

return offset;
}

use it like this:


div.onmousemove = function(evt)
{
var offset = getOffset(evt);
console.log(offset.x+","+offset.y);
}

enjoy 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s