varad
varad

Reputation: 8029

html5 on drag change dragging image or icon

I have a simple html like:

<!DOCTYPE HTML>
<html>
<head>
<style>
    .drag-icon{height: 100px; width: 100px; background-color: red}
</style>
<script>
    function drag(ev) {
        var drag_icon = document.createElement("div")
        drag_icon.className = "drag-icon"

        ev.dataTransfer.setData("text/html", drag_icon);
    }
</script>
</head>
<body>
    <div style="height: 100px; width: 100px; background-color: #CCC" draggable="true" ondragstart="drag(event)">
        Hellooww world
    </div>

</body>
</html>

Here when I drag the div, while dragging my div is being dragged. What I want is when I drag the div the dragging div should be changed to drag_icon.

How can I do this ?

Upvotes: 4

Views: 3478

Answers (1)

hsh
hsh

Reputation: 1855

You should use dataTransfer.setDragImage instead of setData,you also need to append the element to DOM, otherwise you wont be able to see element while dragging. the drag start event should change like this:

var drag = function(e,node) {
   var drag_icon = document.createElement("div")
   drag_icon.className = "drag-icon";
   drag_icon.style.position = "absolute";
   drag_icon.style.top = "-100px";
   drag_icon.style.right = "0px";
   document.body.appendChild(drag_icon);
   e.dataTransfer.setDragImage(drag_icon, 0, 0);  
}

keep in mind that you should append the element to a part of screen that is invisible for users, so position it out side of the window,first I positioned it far right but it causes body to scroll so hide the overflow-x and that's Ok.

body{
  overflow-x:hidden;
}

then I changed the position far top, with this approach there is no need to change body style

There is a working fiddle Here

for more information and complete walk through take a look at Setting a custom ghost image when using HTML5 drag and drop

Upvotes: 1

Related Questions