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.

Easy Drag-and-Drop with 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

jQuery UI logo

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

Dragging hand cursor

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

Mixing desk dials

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

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

Lifebelt

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>

Events: Responding to drags

Bell

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!\n\nOffset: (" + offsetXPos + ", " + offsetYPos + ")\n");
}

</script>

Styling draggable elements

Paintbrush

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

Dropping

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

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" 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:

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:

  1. 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.
  2. Call init() when the document is ready
    We use $( init ) to call our init() function once the DOM has loaded.
  3. 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.
  4. 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.
  5. 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 'cardn', 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
    • 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.
  6. 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:

  1. 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.

  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.
  3. 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.
  • #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.
  • #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.
  • #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.
  • #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.
  • 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!

Number cards game

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):

11-Jun-13 01:25
Hi,

Your Tutorial is great but i really need help to create a game using this tutorial.

I need help to show out some random cards after the user has pulled and dropped to the correct slots.

Can anybody help me?

[Edited by noobie on 11-Jun-13 01:28]
11-Jun-13 02:19
@matt
I need help to show out some random card numbers after the user has pulled and dropped the first card number to the correct slots.
25-Jun-13 02:27
Hi experts,
I am a teacher in Austria and I developed some quizzes with 200 questions in a database for my students taking the great ideas of this example.
But some students using a surface RT can not use my quizzes because drag & drop does not work there and it is not possible to install an other browser like Mozilla or Chrome on a RT system!!!!

Do anybody know a solution of this problem?

Thanks from Salzburg
Uwe
25-Jun-13 05:33
It's not often I comment these days, but the specificity and the comprehensiveness of this article qualifies such a response — you've given me precisely what I need.
06-Jan-14 01:46
Nice tutorial. Im trying to modify this drag and drop so that it is possible to drag and drop each number to multiple slots. Is this possible? Can anyone give me a hint?
06-Jan-14 01:46
Nice tutorial. Im trying to modify this drag and drop so that it is possible to drag and drop each number to multiple slots. Is this possible? Can anyone give me a hint?
06-Jan-14 03:56
Hi robinh,

I've not posted on this thread for a while so forgive me if I am repeating anything said by others.

Anyway ... I've done something similar to your requirements in a music notation application I wrote. In that I need to be able to drag from a palette of musical symbols onto the lines of a music stave. Most of the symbols can be placed multiple times, which seems to be what you want to do (kind of).

My first solution was to create a stack of each symbol and thus have many instances of each to drag.

However, I quickly realised that all I needed to do was REPLACE the symbol in the palette once I'd used (dragged) the previous instance.

There's a setting to say "clone" the dragged object.

A quick search for an example yielded ...

$( ".selector" ).draggable( "option", "helper", 'clone' );

See this for details :

http://stackoverflow.com/questions/7878980/jquery-ui-drag-shape-but-keep-a-copy-of-the-original-shape


Hope this helps.

Chris
06-Jan-14 06:23
Hi Chris,

Thank you for your answer.
I have a modified version of this drag and drop where i also save data to mysql.


Tried to add helper "clone" but after it is dragged to a slot it is gone. Im not sure why this happens but maybe because I declare the div's in the html file and not by js.

Will need to do some more testing on this.

Best regards
Robin
06-Jan-14 07:38
Hi again,

Im actually using this example:

http://stackoverflow.com/questions/19826075/jquery-drag-drop-form-hidden-value-inserting-into-php-mysql

Have not got it to work as i want yet.
Does anyone have a tips?

Code is here:

http://jsfiddle.net/qLhke/29/
13-Jan-14 09:38
Hello, first I want to congratulate you for your tutorial which was undoubtedly very well done! Secondly, I would like to do with my students a similar to this application, but it was recorded all in mysql example a student does something in the application and this is ready, while another home can continue. Hugs and success for all! I used the translator for not writing in English, I apologize if something went wrong. Jean Brazil.
16-Jan-14 11:09
Hi, i need my droppable fires multiple drop events, how can i do that? until now it just fires one. Please im desperate!!!
04-Mar-14 23:59
How would you drag a card that's been locked in place back out again
and
either drag it to another drop target (draggable)
or
revert back to its previous position if unsuccessful (revert)
14-Mar-14 05:51
The tutorial is so nice and easy to understand step by step.

In number cards game, its uses numbers and functionality is place to correct place.

But i need the code for letters (a,b,c,d...) given some letters,
we need to frame a correct name.


for example

n t h l i s e

Using the above letters, i drag or move (left and right only) one by one letter and to form the correct name as following.

"senthil" is the correct name.

Please give a reply.

Any help will be appreciated.
15-Mar-14 20:24
Letters are also numbers ... ASCII code numbers.


Array elements can hold letters as well and are referenced by a number, so just as long as the letters are in the array in their correct final order it will work just the same.

[Edited by chrishirst on 15-Mar-14 20:24]
31-Mar-14 08:43
Thanks for this awesome tutorial. I'm not a programmer but found it really helpful.

I've got what I hope is a simple question. It's about the array for 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."

Instead of the card number appearing on the draggable card, I would like some custom text. Is there a simple way to do that?
01-Apr-14 01:21
"Instead of the card number appearing on the draggable card, I would like some custom text. Is there a simple way to do that?"

I've been bashing my head against this all morning. If someone could tell me the answer, I'd be so grateful.

While I've been failing to make this happen, I've noticed that if you repeatedly refresh the game, about 10% of the time it will not randomise the cards. This is both on my local development version and also on the live preview (http://www.elated.com/res/File/articles/development/javascript/jquery/drag-and-drop-with-jquery-your-essential-guide/card-game.html). Just keep hitting refresh and you'll see that fairly often it gives you all the dragable cards in non-randomised order (1-10).
01-Apr-14 01:33
If it helps, this is where I've got to so far.

If I change the numbers variable to be like this (there are only seven cards in my game):


var numbers = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ];


then everything displays correctly, however, the cards won't match. You cannot drop them in place.

If I make a new variable to store the text values, like this:

var test = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ];


and change the code that creates the cards from this:


$('<div>' + numbers[i] + '</div>')


to be this:


$('<div>' + test[i] + '</div>')


then the cards do not sort and they are also not droppable.
01-Apr-14 21:50
OK, I've finally found the answer. When you create the numbers array, you need to give it multiple properties. Like this:


var numbers = [];
numbers [ 0 ] = {x:1, y:'red'};
numbers [ 1 ] = {x:2, y:'orange'};
numbers [ 2 ] = {x:3, y:'yellow'};
numbers [ 3 ] = {x:4, y:'green'};
numbers [ 4 ] = {x:5, y:'sky blue'};
numbers [ 5 ] = {x:6, y:'indigo'};
numbers [ 6 ] = {x:7, y:'violet'};


All you need to do then is define which property you want when you're making the card stack:


for ( var i=0; i<7; i++ ) {
$('<div>' + numbers[i].y + '</div>').data( 'number', numbers[i].x ).attr( 'id', 'card1' ).appendTo( '#cardPile' ).draggable( {
containment: '#content',
stack: '#cardPile div',
cursor: 'move',
revert: true
} );
}
08-Apr-14 04:55
It looks like no-one is following this, but all the same, the following css will fix the cursor (which changes to 'text select' when hovering over cards/slots):



#cardSlots {
cursor: default;
}

#cardPile {
cursor: move;
}
08-Apr-14 05:05
An updated, improved version of the above:



/* Cursors */
#cardPile div {
cursor: move;
}

#cardSlots {
cursor: default;
}

.correct {
cursor: default;
}

View all 98 responses »

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.

Top of Page