skip to Main Content

I can’t seem to figure out how to change the dragged text, without also changing the original text from the element. I want to change the dragged text shown next to the cursor when moving the text, not while dropping it in a dropzone or when dragging it over a DOM, but while dragging it anywhere.

function drag(dragevent) {
  dragevent.target.innerHTML = 'bar';
  dragevent.dataTransfer.setData("text", dragevent.target.id);
  dragevent.target.style.color = "green";

}
<div id="div1">
  <span id="drag" draggable="true" ondragstart="drag(event)">drag me</span>
</div>
<div id="div2"></div>

2

Answers


  1. Chosen as BEST ANSWER

    Got it work by altering Dimava's answer a little:

    function drag(dragevent) {
      // cleate a clone of the note outside the screen
      let e = dragevent.target.cloneNode(true)
      e.style = 'position: fixed; top: 0; right: 10'
      e.innerText ="bar";
      dragevent.target.after(e)
      dragevent.dataTransfer.setDragImage(e , 0, 0)
      dragevent.dataTransfer.setData("text", dragevent.target.id);
      dragevent.target.style.color = "green";
      setTimeout(() => e.remove(), 1)
    }
    <div id="div1">
      <span id="drag" draggable="true" ondragstart="drag(event)">drag me</span>
    </div>
    <div id="div2"></div>


  2. function drag(dragevent) {
      // cleate a clone of the note outside the screen
      let e = dragevent.target.cloneNode(true)
      e.style = 'position: fixed; top: 0; right: 0'
      dragevent.target.after(e)
    
      // set it as drag image
      dragevent.dataTransfer.setDragImage(e , 10, 10)
    
      // do whatever you want with the original node
      dragevent.target.innerHTML = 'bar';
      dragevent.dataTransfer.setData("text", dragevent.target.id);
      dragevent.target.style.color = "green";
    
      // cleanup the clone on dragend or whenever
      setTimeout(() => e.remove(), 100)
      // requestAnimationFrame(() => e.remove(), 100)
      // requestAnimationFrame does work but sometimes fails to start drag
    }
    <div id="div1">
      <span id="drag" draggable="true" ondragstart="drag(event)">drag me</span>
    </div>
    <div id="div2"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search