Search code examples
htmldrag-and-dropdraggableappearance

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-transparent and follows your cursor until you stop/drop. I'd like to control that so that I can start my drag from anywhere inside an element, but when you actually start dragging, I can have only a small image follow the cursor, exactly where the cursor is.

The practical example is: A list of things to drag, each is a small image and some text for the name of the thing you will be dragging to side of it. I'd like to be able to start my drag anywhere in the element over the image or text, but then only the image follows your cursor, and directly under the cursor, rather than offset from where you started dragging it.

I can think of a few ways to trick it (a hidden element that appears where you mouse cursor is, when you start to drag and is what you actually drag), or resort to classic Javascript drag and drop.

Thanks


Solution

  • 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/