5

I have an HTML5 application which utilizes drag and drop. Essentially the user can drag an image from a "drawer" onto a canvas to create a larger image. I want the elements to drop in the place where they were release. I have this working in all browsers except Firefox.

On the drop event, I am using the following to get the coordinates of the mouse, and calculate the position of the dropped image within the canvas.

var top = evt.originalEvent.offsetX;
var left = evt.originalEvent.offsetY;

The issue is, this property is not available in FF. Is there any other way to get this? Without it, I can't see how to possible drag and move elements within FF.

Note: I am not using the canvas element. I am dropping images to a div. Not sure if that matters.

Sebas
  • 21,192
  • 9
  • 55
  • 109
Chris
  • 4,762
  • 3
  • 44
  • 79
  • http://bugs.jquery.com/ticket/8523 – zb' Nov 17 '12 at 23:29
  • 1
    The bug is not related to jQuery. I am using the HTML5 APIs for Drag and Drop. Sorry, should have specified. – Chris Nov 19 '12 at 16:34
  • This is way more difficult than it should be. Getting the mouse position during an HTML5 drag in Firefox - you'd have thought it would be elementary. – MSC Dec 08 '15 at 05:04
  • It's a bug that's been known for 6 years: https://bugzilla.mozilla.org/show_bug.cgi?id=505521. It is shocking that it's not fixed yet. – MSC Dec 08 '15 at 06:07

3 Answers3

8

Try this in firefox..

var X = event.layerX - $(event.target).position().left;
var Y = event.layerY - $(event.target).position().top;
Kathiravan
  • 689
  • 1
  • 7
  • 22
4

I tried using layerX and layerY but mysteriously they were different from same values in Chrome.

Then I realized that on a Retina display Firefox setDragImage won't take the scale into account.
In other words, calling setDragImage(div, 10, 10) would place the cursor at 5px; 5px point.

Ridiculous, isn't it?

var originalEvent = e.originalEvent,
  offsetX = originalEvent.offsetX,
  offsetY = originalEvent.offsetY;

if (_.isUndefined(offsetX) || _.isUndefined(offsetY)) {
  // Firefox doesn't take scale into account so we need to compensate for it
  offsetX = originalEvent.layerX * (window.devicePixelRatio || 1);
  offsetY = originalEvent.layerY * (window.devicePixelRatio || 1);
}

originalEvent.dataTransfer.setDragImage(el, offsetX, offsetY);
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
0

I tried Kathirvans answer above but it didnt work for me. The magic potion for my page was...

var x = e.originalEvent.pageX - $(this).offset().left;
var y = e.originalEvent.pageY - $(this).offset().top; 
louisinhongkong
  • 551
  • 1
  • 6
  • 13