Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to Drag and Drop in HTML5

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;
});
like image 716
PeteGO Avatar asked Nov 18 '11 22:11

PeteGO


People also ask

How do you drag-and-drop in HTML5?

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.

Is drag-and-drop possible in HTML?

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.


1 Answers

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;
});
like image 199
pimvdb Avatar answered Oct 05 '22 00:10

pimvdb