Hướng dẫn về Drag và Drop (kéo thả) với jQuery

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:
1 2 3 4 5 6 7 8 | <head> ... <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript" src="http://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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <!doctype html> <html lang="en"> <head> <style> #makeMeDraggable { width: 300px; height: 300px; background: red; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript" src="http://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> |
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 containmentoption 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:
1 2 3 4 5 6 7 | function init() { $('#makeMeDraggable').draggable( { containment: '#content', cursor: 'move', snap: '#content' } ); } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <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> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <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> |
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:
1 2 3 4 | <style> #makeMeDraggable { width: 300px; height: 300px; background: red; } #makeMeDraggable.ui-draggable-dragging { background: green; } </style> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <!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="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript" src="http://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> |
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:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <!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="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript" src="http://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
- A "#cardPile" div that will contain the set of 10 unsorted cards
- A "#cardSlots" div 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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 divs 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- Makes the card draggable
- Uses containment to constrain it to the #content div
- Uses stack 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
- 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():

