With the introduction of HTML5 drag and drop has never been this easy. HTML5 includes a Drag and
Drop API which brings about native support for most browsers making coding a breeze.
When creating a drag and drop application in your website you need the following:
- An item which is going to be dragged
- A drop target for the dragged item
- Javascript event handlers on the “drop target” to tell the browser it can drop
In HTML5 <img> an <a href= “ #”> elements are dragable by default. If you want to drag a different element within your website you will have to set the dragable attribute to true. By default the elements can be dragged but are unable to be dropped.
To drop the elements we need to:
- First we need to tell the browser that the given element can be dragged over a specific point.
- Secondly we need to handle the drop event. To do this all we have to do is cancel the dragover event, below is an example:
- var drop = document.querySelector('#YOUR DROP DIV NAME');
// This will tell the browser that we can drop the element in a given location
element.addEventListener(drop, 'dragover', cancel);
- // This will tell the browser that we can drop the element in a given location(IE 9 Support)
element.addEventListener(drop, 'dragenter', cancel);
element.addEventListener(drop, 'drop', function (event) {
// This will stop the browser from redirecting off to the text
if (event.preventDefault) {
event.preventDefault();
}
this.innerHTML += '<p>' + event.dataTransfer.getData('Text')+ '</p>';
return false;
});
//When dragover event is fired (when the user drags the element over another
function cancel(event) {
if (event.preventDefault) {
event.preventDefault();
}
return false;
}
To show the dropped element we need to do 2 things:
- First we need to cancel the default action of the browser. We do this so that the browser does not act as it usually would. For example if we were to drag and drop <a href =”#”> the browser would try and browse to this location.
- Secondly we need to get the contents from the dataTransfer object.
It is possible to drag and drop any elements within a website by assigning the draggable = “true” variable. Remember, Internet Explorer 9 reacts differently to Mozilla, Safari and Google Chrome therefore it is important to use both “dragover” and “dragenter” when setting the drop zone in your code.
Image Source: http://www.interaria.com/dallaswebdesignblog/wp-content/uploads/2011/12/HTML5-drag-and-drop.png