8
votes

Trying to do a simple drag and drop example in HTML5 - but when I drop the image into the div element I get the following error.

Uncaught TypeError: Cannot set property 'innerHTML' of null

So I assume the error message means dragElement is null. I don't understand why though, because I set it in the dragstart event to be the HTML of the img element.

Anyone know how to make this work?

var dragElement = null;

$('#x').bind('dragstart', function (e) {
    dragElement = this;
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
});

$('#drop-box').bind('dragover', function (e) {
    e.preventDefault();
    return false;
});

$('#drop-box').bind('drop', function (e) {
    e.preventDefault();
    if (e.stopPropagation) {
        e.stopPropagation();
    }

    if (dragElement != this) {
        dragElement.innerHTML = this.innerHTML;
        this.innerHTML = e.originalEvent.dataTransfer.getData('text/html');
    }

    return false;
});
1

1 Answers

22
votes

dataTransfer is part of the original event object, not the jQuery one. Use e.originalEvent instead: http://jsfiddle.net/KWut6/.

 e.originalEvent.dataTransfer ...

HTML

<image src="http://lorempixum.com/100/100/" draggable="true" id="x">
<div id="drop-box">a</div>

JavaScript

var dragElement = null;

$('#x').bind('dragstart', function (e) {
    dragElement = this;
    e.originalEvent.dataTransfer.effectAllowed = 'move';
    e.originalEvent.dataTransfer.setData('text/html', this.innerHTML);
});

$('#drop-box').bind('dragover', function (e) {
    e.preventDefault();
    return false;
});

$('#drop-box').bind('drop', function (e) {
    e.preventDefault();
    if (e.stopPropagation) {
        e.stopPropagation();
    }

    if (dragElement != this) {
        dragElement.innerHTML = this.innerHTML;
        this.innerHTML = e.originalEvent.dataTransfer.getData('text/html');
    }

    return false;
});