Search code examples
javascripthtmldrag-and-dropdraggabletailwind-css

How to style the item being dragged with HTML 5 Drag And Drop API


We are using the the HTML 5 Drag and Drop API for a project.

https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API

Everything works ok, and now we need to be able to have different styles for the original item source and for the item being dragged.

The issue we are having is that the item being dragged is always semi-transparent.

We are not allowed to share the code, but this is an examples we used as a base

https://www.w3schools.com/html/html5_draganddrop.asp

<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>

What we need is to

  • Have the original item source background changed to gray
  • Have the item being dragged background changed to blue, and not being semi-transparent.

Thanks for the help.


Solution

  • This concept has been beautifully explained on this page- https://www.kryogenix.org/code/browser/custom-drag-image.html

    The idea is to insert the styled image you want to show as drag image in the body and using css move it out of the view and set that component as 'drag image'.

    Tip: the behaviour is different in different browsers you might wanna test if it works as required as you want in other browsers too.