Skip to content Skip to sidebar Skip to footer

Controlling The Appearance Of The HTML5 Drag And Drop Effect

Is there a way to control the appearance of 'what you are dragging' using the HTML5 Drag and Drop APIs? Normally, whatever HTML element is draggable is what becomes semi-transparen

Solution 1:

I think .setDragImage(element, x, y); might be what you are looking for.

function handleDragStart(e) {
    var dragIcon = document.createElement('img');
    dragIcon.src = 'http://...';
    dragIcon.width = 100;
    e.dataTransfer.setDragImage(dragIcon, x, y);
}

this.addEventListener('dragstart', handleDragStart, false);

Example here: jsfiddle.net/cnAHv/


Solution 2:

Unfortunately, it looks like the spec was built to favor consistent native behavior over in-browser customization.

We did a bunch of research and summarized our findings here:

https://www.inkling.com/engineering/native-html5-drag-drop/

The long and short, though, is that using a helper (like jQuery UI) or rolling your own is generally preferable if you need to do anything sophisticated.

Still, if you'd really like to use the native behavior and setDragImage() isn't adequate, there are a few alternatives.

One particularly extravagant approach could involve hijacking the renderer to create a screenshot (!) of the element as you‘d like it to be styled, and then inserting it via a data URI.

See: http://cburgmer.github.io/rasterizeHTML.js/jsconfeu2013/#/step-4

A saner approach would be to simply absolutely position a ghost element to follow the mouse. But that takes us back to writing code that re-implements core parts of drag behavior outside of the API.


Solution 3:

According to this question on StackOverflow, we cannot change the style of the draggable object while dragging it but we can set a drag image. This will cause a image to appear while dragging the ghost object.

event.dataTransfer.setDragImage(document.getElementById('div2'),50,50);

Explanation:

on dataTransfer we call a setDragImage() function in which we pass the ID of the div and give the position of where the image will appear when we will start dragging it.

See more about dataTransfer here: Mozilla Developers - DataTransfer


Post a Comment for "Controlling The Appearance Of The HTML5 Drag And Drop Effect"