Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html5 Drag and Drop Mouse Position in Firefox

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.

like image 516
Chris Avatar asked Nov 17 '12 23:11

Chris


People also ask

Does HTML5 support drag-and-drop?

Complete HTML/CSS Course 2022 Now HTML 5 came up with a Drag and Drop (DnD) API that brings native DnD support to the browser making it much easier to code up. HTML 5 DnD is supported by all the major browsers like Chrome, Firefox 3.5 and Safari 4 etc.

What is drag-and-drop feature in HTML5 explain with example?

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept which is used to copy, reorder and delete items with the help of mouse. You can hold the mouse button down over an element and drag it to another location. If you want to drop the element there, just release the mouse button.

How drag-and-drop works in HTML?

HTML drag-and-drop uses the DOM event model and drag events inherited from mouse events . A typical drag operation begins when a user selects a draggable element, drags the element to a droppable element, and then releases the dragged element.


2 Answers

Try this in firefox..

var X = event.layerX - $(event.target).position().left;
var Y = event.layerY - $(event.target).position().top;
like image 169
Kathiravan Avatar answered Oct 18 '22 12:10

Kathiravan


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);
like image 28
Dan Abramov Avatar answered Oct 18 '22 13:10

Dan Abramov