Search code examples
javascriptsafaridrag-and-drop

setDragImage on Safari Crashes Unexpectedly


I am having difficulties determining why Safari 6.0+ crashes unexpectedly when trying to use the setDragImage() method.

I have a dragstart event and I would like to attach a background image while this is occuring. The documented way to go about this is to utilize the setDragImage() method on the event wireup. This works perfectly fine in Firefox and Chrome.

I know this is possible because when I run this website with the Safari browser the drag image works perfectly.

However, in my simple example it blows up.

HTML:

 <div  draggable='true' class='dragme'>
  </div>

JavaScript:

var dragMe = document.querySelector('.dragme');

dragMe.addEventListener('dragstart', function(e)
{
    e.dataTransfer.setData('Test', 'some data');   
    var img = document.createElement("img");   
    img.src = "http://kryogenix.org/images/hackergotchi-simpler.png";
    e.dataTransfer.setDragImage(img, 0, 0);
}, false);

CSS:

.dragme
{
  border:1px solid red;
  height:100px;
  background-color:blue;
}

Solution

  • I've determined that if the image element you are using on the setDragImage() method hasn't loaded, the browser will thread abort. The fix is simple. Make sure the image element is loaded before calling the method. The easiest way to do this is to create the image element outside of the event.

    //Preload the image
    var img = document.createElement("img");   
    img.src = "http://kryogenix.org/images/hackergotchi-simpler.png";
    
    dragMe.addEventListener('dragstart', function(e)
    {
        e.dataTransfer.setData('Test', 'some data');   
        e.dataTransfer.setDragImage(img, 0, 0);
    }, false);