Drag and Drop on JavaScript

 Drag and Drop in Javascript

Prerequisites

Dealing a Deck of Cards in Javascript

Description of Video

Topics Covered:

Using jQueryUI (http://jqueryui.com/)

Implementing drag and drop functionality of images

Video

http://www.youtube.com/watch?v=oRBwCb4hOX0

Reference Materials

JSFiddle of code in video is at http://jsfiddle.net/reaglin/YFtBp/

Steps involved in the video code

HTML Involved is simply a button to trigger the dealing of a card and a div to serve as a drop target.

<input type="button" value="Deal Card" id="deal" />
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<div id='drop' class='drop'>Drop Here</div>

2 things you have to do before you can run this code.

  1. Load jQuery and jQuery-ui
  2. Call the initialization function  $(init)

The initialization function simply designates the div to serve as a drop target

function init() {
   $('.drop').droppable( {         // We need a place to drop cards
   drop: handleDropEvent           // and it should handle this event
} ); 
}

In jQuery we can specify the object id=’deal’ to call the function dealCard()

$('#deal').click(function () {
   dealCard();               // Call dealCard() when the user clicks deal
});

Dealing the card does a few easy things, creates an image, gives it an id, and species that it is draggable

function dealCard() {
  var img = document.createElement("img");         // Create an image
  img.src = 'https://YourURL/YourCardImage.png';   // Set the source (graphic)
  img.id = 'MyCreatedCard';                        // Give the image an ID
  document.body.appendChild(img);         // Put the image in the document

  $('#MyCreatedCard').draggable();        // Make the image draggable
}

We told the div to handle a drop event, but we didn’t tell it what to do

function handleDropEvent( event, ui ) {
   // Display the id of the dragged object

   $('#drop').html( ui.draggable.attr('id') );       

}