0

I am currently working on html5 drag and drop. My code is working however, I want to change one effect. When user drags an element then a copy of dragged element should stick to cursor/pointer/arrow. The default behaviour of html5 drag and drop does not look real. If you see jquery UI draggable, the element literally moves with cursor. How can I add this kind of effect with html5 drag and drop?

Below is my code.

html code

<div id="boxA">
   <div id="word1" class="word" draggable="true">HTML5</div>
   <div id="word2" class="word" draggable="true">is</div>
   <div id="word3" class="word" draggable="true">very</div>
   <div id="word4" class="word" draggable="true">useful</div>
   <div id="word5" class="word" draggable="true">indeed</div>
</div>
<div id="boxB"></div>

javascript

$('.word').on('dragstart', dragDefine);
$('#boxA').on('dragover', dragOver);
$('#boxA').on('drop', dragDrop);
$('#boxB').on('dragover', dragOver);
$('#boxB').on('drop', dragDrop);

function dragDefine(ev) {
   ev.originalEvent.dataTransfer.effectAllowed = 'move';
   ev.originalEvent.dataTransfer.setData("text/plain", ev.target.getAttribute('id'));
   ev.originalEvent.dataTransfer.setDragImage(ev.target, 0, 0);
   return true;
}

function dragOver(ev) {
   ev.preventDefault();
}

function dragDrop(ev) {
   var idDrag = ev.originalEvent.dataTransfer.getData("Text");
   ev.target.appendChild(document.getElementById(idDrag));
   ev.preventDefault();
}

jsfiddle

26ph19
  • 773
  • 9
  • 17

1 Answers1

0

You can achieve this via JQuery in this DEMO.

Don't forget to check the external files I added in the Fiddle, they are mandatory for this kind of operation.

This example should show you several kinds of dragging styles, included the one you need that creates a copy of the dragged item.

$(function () {
    $("#draggable").draggable({
        helper: "original"
    });
    $("#draggable2").draggable({
        opacity: 0.7,
        helper: "clone"
    });
    $("#draggable3").draggable({
        cursor: "move",
        cursorAt: {
            top: -12,
            left: -20
        },
        helper: function (event) {
            return $("<div class='ui-widget-header'>I'm a custom helper</div>");
        }
    });
    $("#set div").draggable({
        stack: "#set div"
    });
});

EDIT : Yes I changed my answer as it didn't fit your needs, should be ok now.

user3241019
  • 811
  • 9
  • 20