4.6. Drag-and-Drop

In Scriptaculous, drag-and-drop is accomplished by adding draggable objects and adding droppable objects in Scriptaculous' droppables list.

Creating a draggable object is achieved by calling the Draggable object's constructor, passing in the document id of the element we want to drag.

new Draggable(obj.id,{revert:true});

Creating a Droppable object is achieved by adding the document id of the droppable object to the Scriptaculous Droppables list.

              Droppables.add(obj.id,
              {
                     accept: 'cdragTarget', // css class to accept
                     onDrop: function(dragTarget)      { // action }
              }
              );

The following example displays a list of countries and allows one country to be dropped on the next, showing an alert when this happens.

Example 4-6. dragDrop.html
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Script-Type" content="text/javascript"/> <title>Using Scriptaculous</title> <script src="js/prototype.js" ></script> <script src="js/scriptaculous.js"></script> </head> <body> <P> Drag and drop countries </P> <div id="US" class="country cdropTarget cdragTarget"><P>US</P></div> <div id="UK" class="country cdropTarget cdragTarget"><P>UK</P></div> <div id="france" class="country cdropTarget cdragTarget"><P>France</P></div> <div id="germany" class="country cdropTarget cdragTarget"><P>Germany</P></div> <script type="text/javascript"> var countries = document.getElementsByClassName('country'); ...

Get Prototype and Scriptaculous: Taking the Pain out of JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.