Dragging and dropping can be a very intuitive way for users to interact with your site or web app. People often use drag-and-drop for things like:

Moving email messages into folders

Reordering lists of items

Moving objects in games around, such as cards and puzzle pieces

Drag-and-drop with JavaScript used to be very hard to do — in fact, getting a decent cross-browser version working was next to impossible. However, with modern browsers and a smattering of jQuery, drag-and-drop is now a piece of cake!

In this tutorial we’ll take a look at how to create drag-and-drop interfaces with jQuery, and we’ll finish with a complete drag-and-drop example: a simple number cards game for kids.

jQuery UI



To add drag-and-drop functionality to your pages, you need to include both the jQuery library and the jQuery UI plugin. jQuery UI is a fantastic plugin for jQuery that adds all sorts of useful user interface widgets, effects and behaviours — including drag-and-drop.

The easiest way to include both libraries is to use Google’s CDN, as follows:

<head> ... <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script> ... </head>

Making elements draggable

When you add an element to a web page — such as a div or an image — then that element is fixed in the page. However, using jQuery UI, it’s easy to make any element draggable with the mouse.

To make an element draggable, simply call the draggable() method on it. Here’s a simple example:

<!doctype html> <html lang="en"> <head> <style> #makeMeDraggable { width: 300px; height: 300px; background: red; } </style> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script> <script type="text/javascript"> $( init ); function init() { $('#makeMeDraggable').draggable(); } </script> </head> <body> <div id="content" style="height: 400px;"> <div id="makeMeDraggable"> </div> </div> </body> </html>

View Demo »

Adding draggable options

You can pass lots of options to draggable() to customize the behaviour of the draggable element, like this:

$('#makeMeDraggable').draggable( { option1 : value1 , option2 : value2 , ... } );

Here are some options that you’ll probably want to use often:

containment

By default, you can drag a draggable element anywhere in the page. Usually, though, you want to constrain the element to a certain portion of the page. You can do this by setting the containment option to various values: 'parent' Constrains the draggable to the parent element 'document' Constrains the draggable to the page 'window' Constrains the draggable to the browser window A selector Constrains the draggable to the selected element Array of 4 values ( [x1,y1,x2,y2] ) Constrains the draggable to the specified rectangle

cursor

Changes the mouse cursor during dragging. For example, you can set this option to 'move' to turn the mouse pointer into a move cursor when dragging the element.

snap

Set this to a selector (e.g. snap: '#snapToMe' ) to snap the draggable element to the edges of the selected element. You can also set this option to true to snap the element to any other draggable element in the page.

stack

If you’re making a group of elements draggable — such as a set of cards — you usually want the currently-dragged element to appear on top of the other elements in the group. By setting the stack option to a selector that matches the group of elements, you can make sure this happens. jQuery UI adjusts the z-index properties of the elements so that the currently-dragged element is brought to the top.

For a full list of draggable options see the jQuery UI documentation.

Let’s modify our draggable square example above, and set a few options. Here’s the changed code:

function init() { $('#makeMeDraggable').draggable( { containment: '#content', cursor: 'move', snap: '#content' } ); }

View Demo »

Notice how the box is now constrained to, and snaps to the edges of, the #content div . The cursor also changes to a move cursor while dragging.

Using a helper

Helpers are elements that are dragged instead of the original element. They are useful when you want to leave the original element in place, but still allow the user to drag something from the element to somewhere else in the page. For example, you might want to let the user drag colours from a colour palette on top of objects to colour them.

You use the helper option to set a helper element for the drag operation. Possible values are:

'original' The default value. The dragged element is effectively the helper, and it moves when the user drags it. 'clone' Makes a copy of the element, and moves the copy instead. A function Lets you create a custom helper. You specify a function which accepts an event object and returns the markup for the helper element (or elements). This element is then moved instead of the original.

When using 'clone' or a function to create a helper, the helper is destroyed when the drag operation stops. However, you can use the stop event (see Events: Responding to drags) to retrieve information about the helper — such as its position — before it’s destroyed.

The following example uses a function to create a custom helper element for the drag operation. Again, this is based on the previous examples — I’ve just included the relevant changes here:

<style> #makeMeDraggable { width: 300px; height: 300px; background: red; } #draggableHelper { width: 300px; height: 300px; background: yellow; } </style> ... <script type="text/javascript"> $( init ); function init() { $('#makeMeDraggable').draggable( { cursor: 'move', containment: 'document', helper: myHelper } ); } function myHelper( event ) { return '<div id="draggableHelper">I am a helper - drag me!</div>'; } </script>

View Demo »

Events: Responding to drags

Often when the user drags an element, you want to know when the dragging has started and stopped, as well as the new position of the element. You can do this by binding event handlers to various events that are triggered by the drag operation, like this:

$('#makeMeDraggable').draggable( { eventName : eventHandler , ... } );

Here’s a list of available events:

create

Fired when the draggable element is first created by calling draggable() .

start

Fired when the user first starts dragging the element.

drag

Fired whenever the mouse is moved during the drag operation.

stop

Fired when the user lets go of the mouse button after dragging the element.

Your event handler function should accept 2 arguments:

The event object ( event ).

). A jQuery UI object representing the draggable element ( ui ).

You can use the following 3 properties of the ui object to retrieve information about the dragged element:

helper The jQuery object representing the helper that’s being dragged. If you haven’t set a custom helper using the helper option then this object is the element itself. position An object that contains the position of the dragged element or helper, relative to the element’s original position. The object has 2 properties: left (the x-position of the left edge of the element), and top (the y-position of the top edge of the element). offset An object that contains the position of the dragged element or helper, relative to the document. As with position , the object has left and top properties.

Let’s modify our example so that it displays the final position of the dragged element, relative to the document, when the user releases the mouse button. Here’s the relevant code:

<script type="text/javascript"> $( init ); function init() { $('#makeMeDraggable').draggable( { cursor: 'move', containment: 'document', stop: handleDragStop } ); } function handleDragStop( event, ui ) { var offsetXPos = parseInt( ui.offset.left ); var offsetYPos = parseInt( ui.offset.top ); alert( "Drag stopped!nnOffset: (" + offsetXPos + ", " + offsetYPos + ")n"); } </script>

View Demo »

Styling draggable elements

Sometimes it’s nice to give elements a different look while they’re being dragged. For example, you might want to highlight the dragged element, or add a drop shadow to it so it looks like it’s being lifted off the page.

While an element is actually being dragged, jQuery UI gives the element a CSS class of ui-draggable-dragging . You can then add a CSS rule for this class in order to style the element while the user is dragging it.

Let’s modify our simple draggable square example so that it changes from red to green while it’s being dragged:

<style> #makeMeDraggable { width: 300px; height: 300px; background: red; } #makeMeDraggable.ui-draggable-dragging { background: green; } </style>

View Demo »

Droppables: Accepting draggable elements

So far we’ve learned how to make an element draggable, so that the user can drag it around the page. We’ve also looked at using events to respond to drags and drops.

However, there’s an easier way to deal with drops, and that is to create droppable elements. A droppable element is an element that can accept a draggable element that has been dragged and dropped onto it.

When a draggable is dropped on a droppable, the droppable fires a drop event. By writing an event handler function for the drop event, you can determine which draggable was dropped onto the droppable.

You can also use the over and out events to determine when a draggable is being dragged over or out of a droppable. For more on droppable events, see the jQuery UI docs.

To make an element droppable, you call — you guessed it — droppable() .

Let’s modify our draggable square example to include a droppable element that the square can be dropped onto:

<!doctype html> <html lang="en"> <head> <style> #makeMeDraggable { float: left; width: 300px; height: 300px; background: red; } #makeMeDroppable { float: right; width: 300px; height: 300px; border: 1px solid #999; } </style> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script> <script type="text/javascript"> $( init ); function init() { $('#makeMeDraggable').draggable(); $('#makeMeDroppable').droppable( { drop: handleDropEvent } ); } function handleDropEvent( event, ui ) { var draggable = ui.draggable; alert( 'The square with ID "' + draggable.attr('id') + '" was dropped onto me!' ); } </script> </head> <body> <div id="content" style="height: 400px;"> <div id="makeMeDraggable"> </div> <div id="makeMeDroppable"> </div> </div> </body> </html>

View Demo »

As you can see, we’ve created an event handler function called handleDropEvent() to respond to the droppable’s drop event. As with draggable events, the handler needs to accept an event and a ui object.

The ui object has a draggable property, which is the draggable element that was dragged onto the droppable. Our function uses this object, along with the jQuery attr() method, to retrieve the ID of the dropped element ( "makeMeDraggable" ) and display it using alert() .

Complete example: A drag-and-drop number cards game

A lot of the above concepts are easier to grasp when you see them working in a real example. So let’s make one!

We’re going to build a simple number cards game for young kids. The user is presented with 10 number cards in random order, and 10 slots to drop the cards onto. The object of the game is to drop all 10 cards onto the correct slots. Try out the finished game by clicking the button below:

View Demo »

When playing the game, you can view the page source to see all the markup and JavaScript code.

Step 1: The markup

The HTML for our game is straightforward:

<!doctype html> <html lang="en"> <head> <title>A jQuery Drag-and-Drop Number Cards Game</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script> <script type="text/javascript"> // JavaScript will go here </script> </head> <body> <div id="content"> <div id="cardPile"> </div> <div id="cardSlots"> </div> <div id="successMessage"> <h2>You did it!</h2> <button onclick="init()">Play Again</button> </div> </div> </body> </html>

In the head area we’ve included the jQuery and jQuery UI libraries, and linked to a style.css file which we’ll build in Step 4. We’ve also added a script element for our JavaScript code (which we’ll write in a moment). In the body we have:

A "#content" div to contain the game

to contain the game A "#cardPile" div that will contain the set of 10 unsorted cards

that will contain the set of 10 unsorted cards A "#cardSlots" div that will contain the 10 slots to drop the cards into

that will contain the 10 slots to drop the cards into A "#successMessage" div to display a “You did it!” message, along with a button to play again. (We’ll hide this initially using JavaScript when the page loads.)

Step 2: The init() function

Our first chunk of JavaScript code sets up the game:

var correctCards = 0; $( init ); function init() { // Hide the success message $('#successMessage').hide(); $('#successMessage').css( { left: '580px', top: '250px', width: 0, height: 0 } ); // Reset the game correctCards = 0; $('#cardPile').html( '' ); $('#cardSlots').html( '' ); // Create the pile of shuffled cards var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; numbers.sort( function() { return Math.random() - .5 } ); for ( var i=0; i<10; i++ ) { $('<div>' + numbers[i] + '</div>').data( 'number', numbers[i] ).attr( 'id', 'card'+numbers[i] ).appendTo( '#cardPile' ).draggable( { containment: '#content', stack: '#cardPile div', cursor: 'move', revert: true } ); } // Create the card slots var words = [ 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten' ]; for ( var i=1; i<=10; i++ ) { $('<div>' + words[i-1] + '</div>').data( 'number', i ).appendTo( '#cardSlots' ).droppable( { accept: '#cardPile div', hoverClass: 'hovered', drop: handleCardDrop } ); } }

Let’s break the above code down:

Initialize the correctCards variable

We first set up a variable called correctCards to track the number of correctly-dropped cards. When this reaches 10 then the user has won the game. Call init() when the document is ready

We use $( init ) to call our init() function once the DOM has loaded. Hide the success message

Within the init() function itself, we first hide the #successMessage div , and reduce its width and height to zero so that we can make it “pop out” when the game is won. Reset the game

Since init() can be called after a game has already been played, we set correctCards to zero so that the game can begin again, and also clear out the #cardPile and #cardSlots div s so that we can populate them afresh. Create the pile of shuffled cards

To create the pile of cards, we first make an array, numbers , containing the numbers 1 to 10, then sort the array with a randomizing sort function to shuffle the numbers. Then we loop through each element in the numbers array, creating a div card element for each number. Inside the div we place the number, so that it appears on the card in the page. Once we’ve created the div object, we store the card’s number in a 'number' key inside the object by using jQuery’s data() method. We also give the card div an id of 'card n ' , where n is the card number. This lets us give each card a different colour in the CSS. We then append the card to the #cardPile div . The interesting bit in the loop is, of course, the call to the draggable() method. This: Makes the card draggable

Uses containment to constrain it to the #content div

to constrain it to the Uses stack to ensure that the dragged card always sits on top of the other cards

to ensure that the dragged card always sits on top of the other cards Uses cursor to turn the mouse cursor into a move cursor during the drag, and

to turn the mouse cursor into a move cursor during the drag, and Sets the revert option to true . This makes the card slide back to its initial position when dropped, so that the user can try again. We’ll turn this option off when the user has dragged the card to the correct slot, as we’ll see in a moment. Create the card slots

The last part of the init() function creates the 10 slots to drag the cards onto. We create an array called words that contains the words “one” to “ten”, then loop through the elements of the words array, creating a slot div for each number. As before, we use data() to record the number of the slot, so we can test if the user has dragged the correct card to the correct slot, and we append the slot to the #cardSlots div . This time, we call the droppable() method so that the slot can receive a draggable card. We use the accept option with the selector "#cardPile div" to ensure that the slot will only accept our number cards, and not any other draggable element. The hoverClass option adds a CSS class to a droppable when a draggable is hovered over it — we use this option to add a class of 'hovered' to the element, which we’ll highlight using CSS. Finally, we set up a drop event handler called handleCardDrop() , which is triggered when the user drops a card on the droppable. We’ll write this handler next. You can also use a function with accept in order to limit the types of draggable that your droppable accepts. For more details on the options available with droppable, check out the docs.

Step 3: The handleCardDrop() event handler function

The last piece of JavaScript we’ll write is the event handler for our droppables’ drop events, handleCardDrop() :

function handleCardDrop( event, ui ) { var slotNumber = $(this).data( 'number' ); var cardNumber = ui.draggable.data( 'number' ); // If the card was dropped to the correct slot, // change the card colour, position it directly // on top of the slot, and prevent it being dragged // again if ( slotNumber == cardNumber ) { ui.draggable.addClass( 'correct' ); ui.draggable.draggable( 'disable' ); $(this).droppable( 'disable' ); ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } ); ui.draggable.draggable( 'option', 'revert', false ); correctCards++; } // If all the cards have been placed correctly then display a message // and reset the cards for another go if ( correctCards == 10 ) { $('#successMessage').show(); $('#successMessage').animate( { left: '380px', top: '200px', width: '400px', height: '100px', opacity: 1 } ); } }

Let’s work through this function:

Grab the slot number and card number

The first thing we do is grab the number of the slot that the card was dropped on, as well as the number of the dropped card, so that we can see if they match. As our function is an event handler for the droppable element, we can retrieve the element via the this variable. We then wrap the element inside the $() function to turn it into a jQuery object, then use the data() method to retrieve the value of the 'number' key, and store the value in slotNumber . Similarly, the draggable property of the ui object contains the jQuery object representing the dragged card. By reading its 'number' key using data() , we get the card number, which we store in cardNumber . Remember that we stored the slot and card numbers using data() in the init() function in Step 2. If the card and slot match, drop the card onto the slot

If the 2 numbers match then the correct card was dropped onto the slot. First we add a 'correct' CSS class to the card so that we can change its colour via CSS. We then disable both the draggable and droppable by calling their disable methods. This prevents the user from being able to drag this card, or drag another card onto this slot, again. Find out more about draggable/droppable methods in the draggable and droppable docs. After disabling the card and slot, we position the card directly on top of the slot by calling the position() method. This handy method lets you position any element relative to practically anything else, and also plays nicely with draggable and droppable elements. In this case, we’re positioning the card ( ui.draggable )’s top left corner ( my: 'left top' ) on top of the slot ( $this )’s top left corner ( at: 'left top' ). Finally we set the card’s revert option to false . This prevents the card from being pulled back to its initial position once it has been dropped. We also increment the correctCards variable to keep track of the number of correctly-dropped cards. Check for a win

If correctCards equals 10, we have a winner! We show the success message, then animate it from zero width and height up to its full width and height, creating a zooming effect. The success message includes a Play Again button in the markup that triggers the init() function when clicked, thereby starting a new game.

Step 4: The CSS

The last stage of creating our card game is to style the page, cards and slots using CSS. Here’s the complete style.css file:

/* Add some margin to the page and set a default font and colour */ body { margin: 30px; font-family: "Georgia", serif; line-height: 1.8em; color: #333; } /* Give headings their own font */ h1, h2, h3, h4 { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; } /* Main content area */ #content { margin: 80px 70px; text-align: center; -moz-user-select: none; -webkit-user-select: none; user-select: none; } /* Header/footer boxes */ .wideBox { clear: both; text-align: center; margin: 70px; padding: 10px; background: #ebedf2; border: 1px solid #333; } .wideBox h1 { font-weight: bold; margin: 20px; color: #666; font-size: 1.5em; } /* Slots for final card positions */ #cardSlots { margin: 50px auto 0 auto; background: #ddf; } /* The initial pile of unsorted cards */ #cardPile { margin: 0 auto; background: #ffd; } #cardSlots, #cardPile { 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); } /* Individual cards and slots */ #cardSlots div, #cardPile 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; } #cardSlots div:first-child, #cardPile div:first-child { margin-left: 0; } #cardSlots div.hovered { background: #aaa; } #cardSlots div { border-style: dashed; } #cardPile div { background: #666; color: #fff; font-size: 50px; text-shadow: 0 0 3px #000; } #cardPile 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); } /* Individually coloured cards */ #card1.correct { background: red; } #card2.correct { background: brown; } #card3.correct { background: orange; } #card4.correct { background: yellow; } #card5.correct { background: green; } #card6.correct { background: cyan; } #card7.correct { background: blue; } #card8.correct { background: indigo; } #card9.correct { background: purple; } #card10.correct { background: violet; } /* "You did it!" message */ #successMessage { 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; }

I won’t go into detail with this file, since most of it is either self-explanatory or not relevant to the tutorial. Some rules of interest though:

#cardSlots and #cardPile — the rectangles containing the slots and unsorted cards respectively — are given a 2-pixel dark grey border with rounded corners and a drop shadow.

— the rectangles containing the slots and unsorted cards respectively — are given a 2-pixel dark grey border with rounded corners and a drop shadow. #cardSlots div and #cardPile div select the slots and cards themselves. They’re floated left so they all line up in a horizontal row, and given some padding and the same style border as the #cardSlots and #cardPile rectangles. Additionally, the card slots are given a dashed border, and the cards are given a nice big font for the numbers. The text-shadow property is used to put an outline around the numbers.

select the slots and cards themselves. They’re floated left so they all line up in a horizontal row, and given some padding and the same style border as the and rectangles. Additionally, the card slots are given a dashed border, and the cards are given a nice big font for the numbers. The property is used to put an outline around the numbers. #cardSlots div.hovered is triggered when a card hovers over a slot, thanks to the hoverclass: 'hovered' option we added in Step 2 above. We give this selector a darker grey background, so that the slot is highlighted when a card is hovered over it. This helps the user identify which slot they’re dropping the card onto.

is triggered when a card hovers over a slot, thanks to the option we added in Step 2 above. We give this selector a darker grey background, so that the slot is highlighted when a card is hovered over it. This helps the user identify which slot they’re dropping the card onto. #cardPile div.ui-draggable-dragging is triggered when a card is being dragged (see Styling draggable elements). We give this selector a drop shadow so the card appears to be floating above the page.

is triggered when a card is being dragged (see Styling draggable elements). We give this selector a drop shadow so the card appears to be floating above the page. #card1.correct through #card10.correct select the individual cards once they’ve been correctly placed, due to the call to addClass() that we made inside handleCardDrop() (see Step 3 above). We give each correct card a different colour to create a nice rainbow effect. We can do this because we gave each card a unique id in Step 2.

select the individual cards once they’ve been correctly placed, due to the call to that we made inside (see Step 3 above). We give each correct card a different colour to create a nice rainbow effect. We can do this because we gave each card a unique in Step 2. Finally, #successMessage styles the “You did it!” box, positioning it centrally in the page and giving it a green background, curvy border and box shadow. We set its width and height to zero initially, so we can zoom it in when the user wins the game.

All done!

We’ve now built our drag-and drop card game. Try it out again if you like:

View Demo »

In this tutorial you learned how to use the jQuery and jQuery UI libraries to add drag-and-drop functionality to your web pages. You looked at:

The Draggable plugin, which makes it easy to turn any element into a draggable widget in the page

How to specify options for draggable elements

Using a helper element, which is dragged instead of the draggable element

Working with draggable events to get information about dragged elements

Styling elements while they’re being dragged, and

The Droppable plugin, which lets you easily identify and handle dropped elements.

Finally, we brought all this knowledge together to build a simple drag-and-drop card game for kids.

I hope you found this article helpful. There’s a lot more to draggables and droppables — and jQuery UI, for that matter — than we’ve covered here. For more information, see the jQuery UI website.

Happy coding!

