In this article I will explain how to drag and drop in HTML page using jQuery and JavaScript. In order to drag and drop images I have made use of jQuery UI Draggable and Droppable plugins.
HTML Markup
The HTML Markup consists of two HTML DIV controls dvSource and dvDest. To the dvSource DIV I have added some images which eventually will be dragged and dropped to the dvDest DIV.
<div id="dvSource">
<img alt="" src="images/Chrysanthemum.jpg" />
<img alt="" src="images/Desert.jpg" />
<img alt="" src="images/Hydrangeas.jpg" />
<img alt="" src="images/Jellyfish.jpg" />
<img alt="" src="images/Koala.jpg" />
<img alt="" src="images/Lighthouse.jpg" />
<img alt="" src="images/Penguins.jpg" />
<img alt="" src="images/Tulips.jpg" />
</div>
<hr />
<div id="dvDest">
Drop here
</div>
CSS Styles
The following CSS classes have to be added to the page.
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
img
{
height: 100px;
width: 100px;
margin: 2px;
}
.draggable
{
filter: alpha(opacity=60);
opacity: 0.6;
}
.dropped
{
position: static !important;
}
#dvSource, #dvDest
{
border: 5px solid #ccc;
padding: 5px;
min-height: 100px;
width: 430px;
}
</style>
Drag and Drop jQuery Implementation
The very first thing I have done is inheritance of the jQuery and the jQuery UI CSS and JS files.
Inside the jQuery document ready event handler, I have applied the Draggable plugin to all the images inside the dvSource DIV so they can be dragged and dropped.
To the dvDest DIV I have applied the Droppable plugin so that it can accept the dropped images. As soon as the images are dropped they are appended to the DIV.
I have added JavaScript alert boxes to notify users when the images are dropped successfully and when it is not successful if the images are dropped outside the dvDest DIV.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.24/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://code.jquery.com/ui/1.8.24/themes/blitzer/jquery-ui.css" rel="stylesheet"
type="text/css" />
<script type="text/javascript">
$(function () {
$("#dvSource img").draggable({
revert: "invalid",
refreshPositions: true,
drag: function (event, ui) {
ui.helper.addClass("draggable");
},
stop: function (event, ui) {
ui.helper.removeClass("draggable");
var image = this.src.split("/")[this.src.split("/").length - 1];
if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) {
alert(image + " dropped.");
}
else {
alert(image + " not dropped.");
}
}
});
$("#dvDest").droppable({
drop: function (event, ui) {
if ($("#dvDest img").length == 0) {
$("#dvDest").html("");
}
ui.draggable.addClass("dropped");
$("#dvDest").append(ui.draggable);
}
});
});
</script>
Screenshots
Images Dragged and Dropped from the DIV
JavaScript alert when image is successfully dropped
JavaScript alert when image is dropped outside the DIV
Demo
Downloads