Drag and drop using basic jQuery framework

Anish picture Anish · Mar 6, 2012 · Viewed 9.3k times · Source

Is it possible to achieve drag and drop using basic jQuery script (without using jQuery UI)?

Answer

Harti picture Harti · Mar 6, 2012

In HTML5, there's an attribute called "draggable".

<div draggable='true'>Drag me</div>
<div id='dropzone'>Drop it here!</div>

You could make use of the following events:

var onDragEnter = function(event) {
    event.preventDefault();
    $("#dropzone").addClass("dragover");
}, 

onDragOver = function(event) {
    event.preventDefault(); 
    if(!$("#dropzone").hasClass("dragover"))
        $("#dropzone").addClass("dragover");
}, 

onDragLeave = function(event) {
    event.preventDefault();
    $("#dropzone").removeClass("dragover");
},

onDrop = function(event) {
    event.preventDefault();
    $("#dropzone").removeClass("dragover");
    console.log(event.originalEvent.dataTransfer.files);
};

$("#dropzone")
.on("dragenter", onDragEnter)
.on("dragover", onDragOver)
.on("dragleave", onDragLeave)
.on("drop", onDrop);

Hope that helps for the moment.