Drag and Drop Example With jQuery

Drag and Drop

This tutorial shows an example on how to drag-and-drop the item to the specific location.

Drag-and-Drop can be very useful to interact with the web application. You may 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

You may also like to read jQuery toggle animation.

Prerequisites

Knowledge of HTML, CSS, JavaScript/jQuery

jQuery 1.11.1 – 3.6.0, jQuery UI 1.10.4 – 1.13.2

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

jQuery Drag and Drop Implementation

Drag-and-Drop implementation using JavaScript is very difficult for cross-browser version working but nowadays 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 I have same number of empty slots as many as colors. So, here I am going 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 colors, then you will get success message at the end.

HTML

Inside <body/> tag of the HTML file put the below content. For each <div> area I have put the comment so that it would be easier to understand what each <div> area does.

<body>

	<!--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>

</body>

CSS

I will add some style to the drag-and-drop example. I have added comment to each section’s style for clarification. I have decorated every section, such as, color slots, content area, success message div, error message div, etc. using 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 apply margin from all sides,
* next 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, I will show you the jQuery part that has the important role for drag-and-drop actions. For this jQuery code snippets also I have put comments for each statement, so it will be clearly understandable what each statement does.

//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
		});
	}

}

You can download the entire source code later from the Source Code section.

Testing jQuery Drag and Drop

When you run the above HTML file, you will find below output on the browser. Now you can test drag and drop using jQuery. Drag any of the color boxes and try to drop into bottom box.

jquery drag and drop

You may also like to read jQuery toggle animation.

Source Code

Download

Leave a Reply

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