Drag and Drop example with jQuery

This tutorial shows an example on how to drag-and-drop the item to the specific location. For drag-and-drop functionality please refer to http://jqueryui.com/
Drag-and-Drop can be very useful to interact with the web application. We often use drag-and-drop features in many areas like

  •     moving email from inbox to different folders
  •     ordering of the list items in a web page
  •     moving objects in game such as moving cards from one place to another

Drag-and-Drop implementation using JavaScript is very difficult for cross-browser version working but now-a-days it’s very easy using jQuery UI framework.
I will explain drag-and-drop feature with an example. This example consists of few colors and we have same number of empty slots as many as colors. So here we have to drag the color and drop the color to the appropriate empty slot. If you cannot put the color on the correct empty slot then you will get an error message otherwise if all empty slots are filled with the correct color then you will get success message at the end.

Prerequisites

Knowledge of HTML, CSS, JavaScript/jQuery

http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js

Either you can use CDN or you can also download the file from the above links and use locally.

HTML part

Inside <body/> tag of the HTML file put the below content

//header message
<div class="aboutBox">
  <h1>Drag and Drop with jQuery</h1>
  <h2>Put the below colors at appropriate positions</h2>
</div>

//main content area  
<div id="content">
 
  //color queue where each color will be dragged from
  <div id="colorQueue"> </div>
 
  //initially empty color slots where each dragged color will be dropped on
  <div id="colorSlots"> </div>

  //show error message when correct slot is not selected for drop
  <div id="errorMsg">
    <h3>OOPs! Wrong selection. Please try again.</h3>
  </div>

  //show success message at the end when all colors are dropped correctly
  <div id="successMsg">
    <h2>You made it!</h2>
    <button onclick="suffleColors()">Plot Again</button>
  </div>

</div>

 

CSS part

We will add some style to the drag-and-drop example.

/**
* add style to entire body
* ------------------------
* margin from each side 10px
* line height for each line 1.8em
*/
body {
  margin: 10px;
  font-family: "Georgia", serif;
  line-height: 1.8em;
  color: #333;
}

/**
* font-family for headers
*/
h1, h2, h3 {
  font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}

/**
* main content area where colors and empty slots are placed
* ---------------------------------------------------------
* first we apply margin from all sides,
* next we override top margin by 10px
*
*/
#content {
  margin: auto;
  margin-top: 10px;
  text-align: center;
  -moz-user-select: none;
  -webkit-user-select: none;
}

/**
* header message with border
*/
.aboutBox {
  clear: both;
  text-align: center;
  margin: auto;
  padding: 10px;
  background: #ebedf2;
  border: 1px solid #333;
  width: 910px;
}

.aboutBox h1 {
  font-weight: bold;
  margin: 5px;
  color: #666;
  font-size: 1.5em;
}

/**
* empty slots
*/
#colorSlots {
  margin: 20px auto 0 auto;
  background: #ddf;
}

/**
* color queue
*/
#colorQueue {
  margin: 0 auto;
  background: #ffd;
}

#colorSlots, #colorQueue {
  width: 910px;
  height: 120px;
  padding: 20px;
  border: 2px solid #333;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;
  border-radius: 10px;
  -moz-box-shadow: 0 0 .3em rgba(0, 0, 0, .8);
  -webkit-box-shadow: 0 0 .3em rgba(0, 0, 0, .8);
  box-shadow: 0 0 .3em rgba(0, 0, 0, .8);
}

#colorSlots div, #colorQueue div {
  float: left;
  width: 58px;
  height: 78px;
  padding: 10px;
  padding-top: 40px;
  padding-bottom: 0;
  border: 2px solid #333;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;
  border-radius: 10px;
  margin: 0 0 0 10px;
  background: #fff;
}

#colorSlots div:first-child, #colorQueue div:first-child {
  margin-left: 0;
}

#colorSlots div.hovered {
  background: #aaa;
}

#colorSlots div {
  border-style: dashed;
}

#colorQueue div {
  background: #666;
  color: #fff;
  font-size: 50px;
  text-shadow: 0 0 3px #000;
}

#colorQueue div.ui-draggable-dragging {
  -moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
  -webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
  box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
}

/**
* success message div
* position: absolute because it will be shown as popup
*/
#successMsg {
  position: absolute;
  z-index: 100;
  background: #dfd;
  border: 2px solid #333;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;
  border-radius: 10px;
  -moz-box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
  -webkit-box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
  box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
  padding: 20px;
}

/**
* error message div
*/
#errorMsg {
  background: #dfd;
  border: 2px solid #333;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;
  border-radius: 10px;
  -moz-box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
  -webkit-box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
  box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
  padding: 20px;
  color: red;
  height: 60px;
  width: 380px;
  margin: auto;
  margin-top: 10px;
  position: relative;
}

 

jQuery

Now we will look at the jquery part where actually drag-and-drop happens

<script type="text/javascript">

//used for tracking how many colors correctly dropped on to the empty slots
var colorCount = 0;
//number of colors in the color queue and empty slots
var TotalColors = 10;
//when the dom is ready call the function suffleColors
$(document).ready( suffleColors );

function suffleColors() {

//initially hide the success message box
$('#successMsg').hide();

//initially hide the error message box
$('#errorMsg').hide();

//initially set value 0
colorCount = 0;
//initially empty string for colors and empty slots
$('#colorQueue').html( '' );
$('#colorSlots').html( '' );

// Create the color queue with the color codes
var colorCodes = [ '8B0000', 'FF1493', 'FF8C00', 'FFFF00', '9400D3', '006400', '00008B', 'A52A2A', 'F5F5F5', '808080' ];
colorCodes.sort( function() { return Math.random() - .5 } );

//iterate colorCodes array and put the colors in a div. Apply jquery ui draggable() with the div so that user can drag the color
//data - we put the color codes as key/value('color'/colorCodes[i]) pairs in attribute called 'data'
//attr - we give each div a unique id with color code
//appendTo - where we will put the colors
//draggable - jquery ui function for drag functionality
//containment - constrains dragging to within the bounds of the specified element or region
//stack - controls the z-index of the set of elements that match the selector, always brings the currently dragged item to the front.
//cursor - mouse curson during the drag
//revert - Whether the element should revert to its start position when dragging stops.
//        Multiple types supported:
//        Boolean: If set to true the element will always revert.
//        String: If set to "invalid", revert will only occur if the draggable has not been dropped on a droppable. For "valid", it's the other way around.
//        Function: A function to determine whether the element should revert to its start position. The function must return true to revert the element.
for ( var i = 0; i < TotalColors; i++ ) {
$('<div style="background-color:'+ '#' + colorCodes[i] +'"></div>').data( 'color', colorCodes[i] ).attr( 'id', colorCodes[i] ).appendTo( '#colorQueue' ).draggable( {
containment: '#content',
stack: '#colorQueue div',
cursor: 'move',
revert: true
} );
}

// Create the color slots with color codes and color names
var tempColorCodes = [ '8B0000', 'FF1493', 'FF8C00', 'FFFF00', '9400D3', '006400', '00008B', 'A52A2A', 'F5F5F5', '808080' ];
var colors = [ 'Dark red', 'Deep Pink', 'Dark Orange', 'Yellow', 'Dark Violet', 'Dark Green', 'Dark Blue', 'Brown', 'White Smoke', 'Gray' ];
//data - we put the color codes in the attribute 'data' as a key/value pair
//droppable - jquery ui function for drop functionality
//accept - A draggable with the same scope value as a droppable will be accepted by the droppable.
//drop - function handleColorDrop has been used to handle the droppable items
for ( var i = 0; i < TotalColors; i++ ) {
$('<div>' + colors[i] + '</div>').data( 'color', tempColorCodes[i] ).appendTo( '#colorSlots' ).droppable( {
accept: '#colorQueue div',
hoverClass: 'hovered',
drop: handleColorDrop
} );
}

}

function handleColorDrop( event, ui ) {
var slotNumber = $(this).data( 'color' );
var colorNumber = ui.draggable.data( 'color' );

// If the color was dropped to the correct slot,
// position it directly on top of the dashed slot
// and prevent it being dragged again
if ( slotNumber === colorNumber ) {
//if dropped on correct slot then hide the error message box
$('#errorMsg').hide();
//disable draggable
ui.draggable.draggable( 'disable' );
//disable droppable
$(this).droppable( 'disable' );
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
ui.draggable.draggable( 'option', 'revert', false );
//track how many colors have been dropped on the slots
colorCount++;
} else {
//show the error message if correct slot not selected for drop
$('#errorMsg').show();
}

// If all the colors have been placed correctly then display a message
if ( colorCount == TotalColors ) {
$('#successMsg').show();
$('#successMsg').animate( {
left: '50%',
top: '50%',
margin: '-50px 0 0 -200px',
width: '400px',
height: '100px',
opacity: 1
} );
}

}

</script>

 

Put all together

<!doctype html>
<html>
<head>

<title>jQuery Drag and Drop example</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<style type="text/css">
/**
* add style to entire body
* ------------------------
* margin from each side 10px
* line height for each line 1.8em
*/
body {
margin: 10px;
font-family: "Georgia", serif;
line-height: 1.8em;
color: #333;
}

/**
* font-family for headers
*/
h1, h2, h3 {
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}

/**
* main content area where colors and empty slots are placed
* ---------------------------------------------------------
* first we apply margin from all sides,
* next we override top margin by 10px
*
*/
#content {
margin: auto;
margin-top: 10px;
text-align: center;
-moz-user-select: none;
-webkit-user-select: none;
}

/**
* header message with border
*/
.aboutBox {
clear: both;
text-align: center;
margin: auto;
padding: 10px;
background: #ebedf2;
border: 1px solid #333;
width: 910px;
}

.aboutBox h1 {
font-weight: bold;
margin: 5px;
color: #666;
font-size: 1.5em;
}

/**
* empty slots
*/
#colorSlots {
margin: 20px auto 0 auto;
background: #ddf;
}

/**
* color queue
*/
#colorQueue {
margin: 0 auto;
background: #ffd;
}

#colorSlots, #colorQueue {
width: 910px;
height: 120px;
padding: 20px;
border: 2px solid #333;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
-moz-box-shadow: 0 0 .3em rgba(0, 0, 0, .8);
-webkit-box-shadow: 0 0 .3em rgba(0, 0, 0, .8);
box-shadow: 0 0 .3em rgba(0, 0, 0, .8);
}

#colorSlots div, #colorQueue div {
float: left;
width: 58px;
height: 78px;
padding: 10px;
padding-top: 40px;
padding-bottom: 0;
border: 2px solid #333;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
margin: 0 0 0 10px;
background: #fff;
}

#colorSlots div:first-child, #colorQueue div:first-child {
margin-left: 0;
}

#colorSlots div.hovered {
background: #aaa;
}

#colorSlots div {
border-style: dashed;
}

#colorQueue div {
background: #666;
color: #fff;
font-size: 50px;
text-shadow: 0 0 3px #000;
}

#colorQueue div.ui-draggable-dragging {
-moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
-webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
}

/**
* success message div
* position: absolute because it will be shown as popup
*/
#successMsg {
position: absolute;
left: 580px;
top: 250px;
width: 0;
height: 0;
z-index: 100;
background: #dfd;
border: 2px solid #333;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
-moz-box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
-webkit-box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
padding: 20px;
}

/**
* error message div
*/
#errorMsg {
background: #dfd;
border: 2px solid #333;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
-moz-box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
-webkit-box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
box-shadow: .3em .3em .5em rgba(0, 0, 0, .8);
padding: 20px;
color: red;
height: 60px;
width: 380px;
margin: auto;
margin-top: 10px;
position: relative;
}
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">

var colorCount = 0;
var TotalColors = 10;
$(document).ready( suffleColors );

function suffleColors() {

// initially hide the success message box
$('#successMsg').hide();

//initially hide the error message box
$('#errorMsg').hide();

// Reset to default
colorCount = 0;
$('#colorQueue').html( '' );
$('#colorSlots').html( '' );

// Create the color queue with the color codes
var colorCodes = [ '8B0000', 'FF1493', 'FF8C00', 'FFFF00', '9400D3', '006400', '00008B', 'A52A2A', 'F5F5F5', '808080' ];
colorCodes.sort( function() { return Math.random() - .5 } );

for ( var i = 0; i < TotalColors; i++ ) {
$('<div style="background-color:'+ '#' + colorCodes[i] +'"></div>').data( 'color', colorCodes[i] ).attr( 'id', colorCodes[i] ).appendTo( '#colorQueue' ).draggable( {
containment: '#content',
stack: '#colorQueue div',
cursor: 'move',
revert: true
} );
}

// Create the color slots with color codes and color names
var tempColorCodes = [ '8B0000', 'FF1493', 'FF8C00', 'FFFF00', '9400D3', '006400', '00008B', 'A52A2A', 'F5F5F5', '808080' ];
var colors = [ 'Dark red', 'Deep Pink', 'Dark Orange', 'Yellow', 'Dark Violet', 'Dark Green', 'Dark Blue', 'Brown', 'White Smoke', 'Gray' ];
for ( var i = 0; i < TotalColors; i++ ) {
$('<div>' + colors[i] + '</div>').data( 'color', tempColorCodes[i] ).appendTo( '#colorSlots' ).droppable( {
accept: '#colorQueue div',
hoverClass: 'hovered',
drop: handleColorDrop
} );
}

}

function handleColorDrop( event, ui ) {
var slotNumber = $(this).data( 'color' );
var colorNumber = ui.draggable.data( 'color' );

// If the color was dropped to the correct slot,
// position it directly on top of the dashed slot
// and prevent it being dragged again
if ( slotNumber === colorNumber ) {
//if dropped on correct slot then hide the error message box
$('#errorMsg').hide();
//disable draggable
ui.draggable.draggable( 'disable' );
//disable droppable
$(this).droppable( 'disable' );
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
ui.draggable.draggable( 'option', 'revert', false );
//track how many colors have been dropped on the slots
colorCount++;
} else {
//show the error message if correct slot not selected for drop
$('#errorMsg').show();
}

// If all the colors have been placed correctly then display a message
if ( colorCount == TotalColors ) {
$('#successMsg').show();
$('#successMsg').animate( {
left: '50%',
top: '50%',
margin: '-50px 0 0 -200px',
width: '400px',
height: '100px',
opacity: 1
} );
}

}

</script>

</head>
<body>

<div class="aboutBox">
<h1>Drag and Drop with jQuery</h1>
<h2>Put the below colors at appropriate positions</h2>
</div>

<div id="content">

<div id="colorQueue"> </div>
<div id="colorSlots"> </div>

<div id="errorMsg">
<h3>OOPs! Wrong selection. Please try again.</h3>
</div>

<div id="successMsg">
<h2>You made it!</h2>
<button onclick="suffleColors()">Plot Again</button>
</div>

</div>

</body>
</html>

 

 

Screen Output

jQuery drag-and-drop example
Thanks for reading. Please do not forget to leave a comment.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *