9

I just want to know how to change the style of the object we are dragging using HTML5's Drag/Drop API. I searched over the net but found nothing! Saw this tutorial but it did't gave me information about styling the object while dragging it.

Any solutions to this problem?

Moreover, Is this possible?

1 Answer 1

9

It is partially possible In HTML5 you are not able to change the style of the ghost object but you are able to change the default ghost object with the setDragImage method from the DataTransfer object. Made an example here (the blu div will become a red div when dragged):

  <style>
      #div1{
        background-color:blue;
        width:100px;
        height:100px;
      }
      #div2{
        background-color:red;
        width:100px;
        height:100px;
      }
    </style>
    ...
    <div id="div1" draggable="true" ></div>
    <br/>
    <div id="div2" ></div>
    <script>
      document.getElementById('div1').addEventListener('dragstart', function(event) {
        event.dataTransfer.setDragImage(document.getElementById('div2'),50,50);
      });
    </script>

http://jsfiddle.net/ftX3C/

So you can't change the style, but have a hidden element from which to use as a ghost image. It can also be an img or a canvas.

I recommend the following tutorial about html5 drag and drop: http://www.html5rocks.com/en/tutorials/dnd/basics/

also read about the DataTransfer object after you finish that tut: developer.mozilla.org/en-US/docs/Web/API/DataTransfer

4
  • Worked fine! i'm added also e.offsetX, e.offsetY as 2th and 3th params instead 50, 50. Thank you! Commented Mar 13, 2016 at 15:46
  • 3
    This doesn’t change the image while dragging, but only at the beginning of dragging. Commented Feb 23, 2017 at 15:54
  • @MichaelSchmid , did you find a way to change the style while dragging?
    – Lossan
    Commented Mar 24, 2020 at 9:35
  • No @Lossan, I didn’t. I then gave up with the Drag-and-Drop API (for this and other reasons) and happily solved my problems with a JavaScript library. Commented May 24, 2020 at 21:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.