HTML5 Drag and Drop anywhere on the screen

Drag and drop doesn’t move elements around, if you want the element to move when you drop it then you have to set the new position of the element in the drop event. I’ve done an example which works in Firefox and Chrome, here are the key points:

function drag_start(event) {
    var style = window.getComputedStyle(event.target, null);
    event.dataTransfer.setData("text/plain",
    (parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
} 

The dragstart event works out the offset of the mouse pointer from the left and top of the element and passes it in the dataTransfer. I’m not worrying about passing the ID because there’s only one draggable element on the page – no links or images – if you have any of that stuff on your page then you’ll have to do a little more work here.

function drop(event) {
    var offset = event.dataTransfer.getData("text/plain").split(',');
    var dm = document.getElementById('dragme');
    dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
    dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
    event.preventDefault();
    return false;
}

The drop event unpacks the offsets and uses them to position the element relative to the mouse pointer.

The dragover event just needs to preventDefault when anything is dragged over. Again, if there is anything else draggable on the page you might need to do something more complex here:

function drag_over(event) {
    event.preventDefault();
    return false;
} 

So bind it to the document.body along with the drop event to capture everything:

var dm = document.getElementById('dragme');
dm.addEventListener('dragstart',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',drop,false); 

If you want this to work in IE you’ll need to convert the aside to an a element, and, of course, all the event binding code will be different. The drag and drop API doesn’t work in Opera, or on any mobile browsers as far as I’m aware. Also, I know you said you don’t want to use jQuery, but cross browser event binding and manipulating element positions are the sort of things that jQuery makes much easier.

Leave a Comment