Drag-and-Drop with jQuery: Your Essential Guide
Learn how to use jQuery, and the jQuery UI Draggable and Droppable plugins, to create drag-and-drop interfaces in your web pages. Includes a full drag-and-drop card game example.
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="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:
<!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 thecontainmentoption 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 totrueto 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
stackoption to a selector that matches the group of elements, you can make sure this happens. jQuery UI adjusts thez-indexproperties 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'
} );
}
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
eventobject 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>
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
helperoption 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), andtop(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 hasleftandtopproperties.
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!\n\nOffset: (" + 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:
<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:
<!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:
<!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"divto contain the game - A
"#cardPile"divthat will contain the set of 10 unsorted cards - A
"#cardSlots"divthat will contain the 10 slots to drop the cards into - A
"#successMessage"divto 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
correctCardsvariable
We first set up a variable calledcorrectCardsto 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 ourinit()function once the DOM has loaded. -
Hide the success message
Within theinit()function itself, we first hide the#successMessagediv, and reduce its width and height to zero so that we can make it "pop out" when the game is won. -
Reset the game
Sinceinit()can be called after a game has already been played, we setcorrectCardsto zero so that the game can begin again, and also clear out the#cardPileand#cardSlotsdivs 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 thenumbersarray, creating adivcard element for each number. Inside thedivwe place the number, so that it appears on the card in the page. Once we've created thedivobject, we store the card's number in a'number'key inside the object by using jQuery'sdata()method.
We also give the carddivanidof'cardn', wherenis the card number. This lets us give each card a different colour in the CSS. We then append the card to the#cardPilediv.
The interesting bit in the loop is, of course, the call to thedraggable()method. This:
- Makes the card draggable
- Uses
containmentto constrain it to the#contentdiv - Uses
stackto ensure that the dragged card always sits on top of the other cards - Uses
cursorto turn the mouse cursor into a move cursor during the drag, and - Sets the
revertoption totrue. 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 theinit()function creates the 10 slots to drag the cards onto. We create an array calledwordsthat contains the words "one" to "ten", then loop through the elements of thewordsarray, creating a slotdivfor each number. As before, we usedata()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#cardSlotsdiv.
This time, we call thedroppable()method so that the slot can receive a draggable card. We use theacceptoption with the selector"#cardPile div"to ensure that the slot will only accept our number cards, and not any other draggable element. ThehoverClassoption 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 adropevent handler calledhandleCardDrop(), 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
acceptin 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 thethisvariable. We then wrap the element inside the$()function to turn it into a jQuery object, then use thedata()method to retrieve the value of the'number'key, and store the value inslotNumber.
Similarly, thedraggableproperty of theuiobject contains the jQuery object representing the dragged card. By reading its'number'key usingdata(), we get the card number, which we store incardNumber.Remember that we stored the slot and card numbers using
data()in theinit()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 theirdisablemethods. 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 theposition()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'srevertoption tofalse. This prevents the card from being pulled back to its initial position once it has been dropped. We also increment thecorrectCardsvariable to keep track of the number of correctly-dropped cards. -
Check for a win
IfcorrectCardsequals 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 theinit()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:
#cardSlotsand#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.#cardSlots divand#cardPile divselect 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#cardSlotsand#cardPilerectangles. Additionally, the card slots are given a dashed border, and the cards are given a nice big font for the numbers. Thetext-shadowproperty is used to put an outline around the numbers.#cardSlots div.hoveredis triggered when a card hovers over a slot, thanks to thehoverclass: '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.#cardPile div.ui-draggable-draggingis 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.correctthrough#card10.correctselect the individual cards once they've been correctly placed, due to the call toaddClass()that we made insidehandleCardDrop()(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 uniqueidin Step 2.- Finally,
#successMessagestyles 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:
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!
Follow Elated
Related articles
Responses to this article
20 most recent responses (oldest first):
That was a great example, but I was wondering if you know of any other resources that go into the concept a bit deeper; I haven't come across any tutorials or training that really lays it out.
@matt, this article has been invaluable as well!
I don't really know of any other resources. I didn't find anything on the web to get me going down this route.
There were three influences that drove me to use a "model" -
a) I am using Grails and it's clear distinction between Model, View and Controller were at the front of my mind at the time. I've done a lot of GUI application work over the years to tend to use this approach as default
b) Complexity of what I wanted to store - my application needs to maintain pretty darn complex state and I needed to have it in an actual data structure rather than rely on the DOM states.
c) Load/Save - My application requires me to be able to persist my visual representation and be able to reload it. Once you have your stuff represented in a data structure (the "model" in JavaScript with the member fields and the getters and setters and convenience functions) it's not too difficult to puke that out in something like JSON. Once you've done it in that direction (saving) you can do the other direction (loading). I tend to have a function called
inflate(jsonString)
in my models and it just takes the JSON string input and calls a library function to reestablish the proper model instance from it.
I don't know if this helps at all. My general advice would be to think about a model/data structure that would hold all the state(s) your thing needs. Maybe even write some tests to use the model until you're happy with it. At that point you can move to doing the visual stuff on top.
One of the first things the appealed to me with jQuery was the ability to attach data to visual objects using
$(locator).data(your-bit-of-data)
Once you do that it makes it nice and clean to access this data inside a drop method (if you're using drag and drop) and use that as the param for your calls to your model functions.
Not sure if this makes it clearer or most confusing!
Chris
Currently I am putting together a checkers board game. I started by implementing the <canvas> element and tried a couple related JS libraries for working with it, but it proved too complicated. Now I'm working with jQuery and <div> elements to create the game board, but I am still figuring out how to best reference the individual cells for the game logic.
I haven't delved into JSON yet but I've been hearing about it a lot.
Anyways, I appreciate that you have taken the time to provide such valuable information!
However, I am having a problem. I am using a function to create a helper (instead of clone), but I am trying to pass a variable to this helper. More specifically, I am trying to pass the inner html of the original draggable element to the helper element.
Here is my very lame attempt:
function catHelper(event, ui){
var name=ui.draggable.html();
return '<div class="cat_helper">'+name+'</div>';
}
One way to do what you need is to have <div>s for the black and white pieces and 8x8 <div>s for the playing board.
If you want to identify the colour of a piece (or counter or whatever you want to call it) you could apply a .data("black") or .data("white"). However - you might want to use the css class attribute since you'll probably be needed to style these <div>s to have a black or white image.
Then on the board each of the squares could have data in the range .data("1,1") ... .data("8,8").
If you make the board squares droppable, and the playing piece draggable then when you drop a piece onto a square you should be able to work out the piece colour and the grid reference in the handleDrop function (which gives you a reference to both the draggable and the droppable)
Once you have these you could call your model method like
model.setCell( x, y, pieceColour )
Something along those lines should work I'd have thought.
http://www.elated.com/articles/json-basics/
@nicolasmoise: Off the top of my head, you probably want to create a closure, passing in the draggable element so that your function can access it.
In the tutorial, the numbers get located randomly in the Card Pile, and the Card Slots are located 1-10, left to right --- Card "1" will always drop on the first Slot.
I want to build a game where you don't know which 'Correct' slot the number should drop into - in other words, so slot "1" (array position 0) locates randomly in the row of 10 Card Slot locations, instead of always in the first (left-most) location, but i've had no luck 'sorting' the Slots to any other position.
any ideas?
tia
One issue I came across was reassigning the parent div of the draggable object when a drop occurred. You can get some positioning weirdness.
If anyone runs across the same problem, you can see my solution here: http://eightbitswitch.com/2012/06/jquery-ui-drag-and-drop-to-change-parent-div/
@danahartweg: Thanks for posting that solution
I have a project in mind, so will try to get to grips with this
Taking the card example as a starting point, I would like to add multiple instances of the same card(s) and stack them on top of each other, (or nearly on top, so you can tell its a stack).
Grateful for an approach
I would like to set this up for my students where they can practice vocabulary, but I am still relatively new to jquery.
How would I go about replacing the numerals with images so that an image could be dragged onto the correct word?
Thanks in advance!
cheers
sameera
<script type="text/javascript">
$(document).ready(function(){
var radius = 200; // radius of the circle
var fields = $('.field'),
container = $('#container'),
width = container.width(),
height = container.height(),
angle = 0,
step = (2*Math.PI) / fields.length;
fields.each(function() {
var x = Math.round(width/2 + radius * Math.cos(angle) - $(this).width()/2),
y = Math.round(height/2 + radius * Math.sin(angle) - $(this).height()/2);
$(this).css({
left: x + 'px',
top: y + 'px'
});
angle += step;
});
});
</script>
</head>
<body>
<div id="container">
<!-- <div id="center"></div>
<div id="crosshair-x"></div>
<div id="crosshair-y"></div>-->
<div class="field">1</div>
<div class="field">2</div>
<div class="field">3</div>
<div class="field">4</div>
<div class="field">5</div>
<div class="field">6</div>
<div class="field">7</div>
<div class="field">8</div>
<div class="field">9</div>
</div>
Any ideas on how I can incorporate this into the drag and drop code so that it works with 9 slots and cards arranged in a circle?
[Edited by peterbrowne on 20-Dec-12 02:11]
what can i do ?
Post a response
Want to add a comment, or ask a question about this article? Post a response.
To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.
