HTML5 with jQuery - e.offsetX undefined in Firefox

On my HTML5 page, I have a div with a mousemove event as follows:

 $('#canvas').mousemove(function(e){ xpos = e.offsetX; ypos = e.offsetY; $('#mouse').html("X : " + xpos + " ; Y : " + ypos); }); 

It works great with Google Chrome. But in Firefox, both values ​​give undefined . I checked it with Firebug, i.e. registered an e object for the console. Found that offsetX and offsetY undefined .

When I searched on Google, there was a solution that I should use layerX and layerY if both offsetX and offsetY are undefined. But from Firebug I could not find it. And even I gave him a try like this:

 xpos = (e.offsetX==undefined)?e.layerX:e.offsetX; ypos = (e.offsetY==undefined)?e.layerY:e.offsetY; 

But it also gives undefined as values.

I am using the latest jQuery - v1.8.2. And I am testing in my Firefox v14.0.1

Any ideas or suggestions?




EDIT

Thanks distro and vusan for helping me. The solution to the above problem is as follows:

Decision

 $('#canvas').mousemove(function(e){ $('#cursor').show(); if(e.offsetX==undefined) // this works for Firefox { xpos = e.pageX-$('#canvas').offset().left; ypos = e.pageY-$('#canvas').offset().top; } else // works in Google Chrome { xpos = e.offsetX; ypos = e.offsetY; } $('#mouse').html("X : " + xpos + " ; Y : " + ypos); }); 
+56
jquery html5 events undefined
Oct 03 '12 at 8:35
source share
5 answers

Try using layerX and layerY for Firefox and offsetX for another browser.

If the event is fired using jquery:

 xpos = e.offsetX === undefined ? e.originalEvent.layerX : e.offsetX; ypos = e.offsetY === undefined ? e.originalEvent.layerY : e.offsetY; 

If the event is fired using javascript:

 xpos = e.offsetX==undefined?e.layerX:e.offsetX; ypos = e.offsetY==undefined?e.layerY:e.offsetY; 
+19
Oct 03
source share

Use layerX and layerY in FF and offsetX and offsetY in all other browsers.

 $('#canvas').mousemove(function(e){ xpos = e.offsetX === undefined ? e.originalEvent.layerX : e.offsetX; ypos = e.offsetY === undefined ? e.originalEvent.layerY : e.offsetY; $('#mouse').html("X : " + xpos + " ; Y : " + ypos); }); 
+19
Dec 05 '13 at
source share

You did not find them, because it is in the original. try: e.originalEvent.layerX e.originalEvent.layerY

About pageX and pageY they do not calculate the same thing. layerX is the left object from the first relative / absolute parent. pageX - to the left of the object from the page.

+14
Jan 08 '13 at 9:00
source share

This works great in firefox and others.

 var offsetRequired = (e.offsetX || e.pageX - $(e.target).offset().left); 
0
Nov 05 '15 at
source share

Firefox actually supports MouseEvent.offsetX and MouseEvent.offsetY after the release of 39.0, which was released in July 2015 .

0
Jul 12 '16 at 14:45
source share



All Articles