I am trying to use .setDragImage
on an anchor element to customize its image when it is being dragged. For some reason, it works perfectly in Chrome but not in Safari. Here is an example:
const drag = document.getElementById("drag");
const testEl = document.createElement("div");
testEl.innerText = "Drag Info";
drag.ondragstart = (event)=>{
document.body.appendChild(testEl);
event.dataTransfer.setDragImage(testEl, 0, 0);
setTimeout(()=>{
testEl.remove();
}, 1);
};
<a id="drag" href="javascript:console.log('clicked')">Drag Me</a>
Notice that when dragging, in Safari a special box with the link is displayed, while in Chrome it correctly says "Drag Info"
It turns out that in order to add a drag image to an element you must set its draggable
property equal to true.
E.g
<a href="...">Link</a>
Should be
<a href="..." draggable="true">Link</a>
Fixed example:
const drag = document.getElementById("drag");
const testEl = document.createElement("div");
testEl.innerText = "Drag Info";
drag.ondragstart = (event)=>{
document.body.appendChild(testEl);
event.dataTransfer.setDragImage(testEl, 0, 0);
setTimeout(()=>{
testEl.remove();
}, 1);
};
<a draggable="true" id="drag" href="javascript:console.log('clicked')">Drag Me</a>