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;
});
Drag and Drop (DnD) is powerful User Interface concept which makes it easy to copy, reorder and deletion of items with the help of mouse clicks. This allows the user to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there.
HTML Drag and Drop interfaces enable applications to use drag-and-drop features in browsers. The user may select draggable elements with a mouse, drag those elements to a droppable element, and drop them by releasing the mouse button.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With