I want to show a ghost element instead of the default browser preview while dragging and dropping. However, in Firefox, the image inside the ghost element is not displayed during dragging. Oddly enough, if I drop it and then drag again, the image does appear.
It seems like this could be a cache-related issue, but I'm unsure how to pre-cache the image in this scenario.
Here's the code snippet:
//html:
<div class="parent container">
<img class="element" src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg" draggable="true" />
</div>
//js:
document.querySelector(".element").addEventListener("dragstart", function(e) {
var img = document.createElement("img");
var div = document.createElement('div');
div.style.width = '100px';
div.style.height = '100px';
div.style.position = 'fixed';
div.style.top = '-1000000px';
div.style.left = '-1000000px';
div.style.border = '2px solid red';
img.src = "http://www.thekrausemouse.com/wp-content/uploads/2016/03/Sample.jpg";
img.style.width = '100px';
img.style.height = '100px';
div.appendChild(img);
document.body.appendChild(div);
e.dataTransfer.setData('text/plain', 'test');
e.dataTransfer.setDragImage(div, 0, 0);
}, false);
Fiddle: https://jsfiddle.net/etseq5cg/5/
Follow these steps to recreate the issue:
1) Open the fiddle or run the snippet
2) Try to drag the sample image
Actual: You will only see an empty square with red border
Expected: You should see a square with the image inside
To reproduce the issue, you may need to force-reload the page (Ctrl+F5). This suggests that the problem might be related to caching.
Note: Removing the ghost element from the DOM in the dragend handler is not relevant to this case.
Update:
1) The real use-case involves a view with a large number of images (~500), so pre-caching images with JS is not a viable solution.
2) For those who couldn't replicate the issue, here's a screenshot: the initial preview after a hard reload (Ctrl+F5) and then the second drag attempt. It's worth noting that no HTTP requests are shown in the network tab of the web inspector in either case. https://i.stack.imgur.com/tAgRW.png