Login Register

List Rearrangement

Yes, you can use Drag and Drop outside of the kitchen! One popular application is rearranging lists. You can do this by enabling list items as drag sources and the list itself as a drop target. That seems kind of wierd at first - you do not expect drag sources and drop targets to overlap, much less contain one another. Here, it helps to think of dragging and dropping as a shortcut for cut-and-paste.

In this example you can drag the elements, Jim Hendrix albums, into whatever order you wish.

<html><head>
<script type="text/javascript" src="/path/to/dojo.js"></script>
<script type="text/javascript">
dojo.require("dojo.dnd.*");

   dojo.require("dojo.dnd.event.*");

   function initList() {
      // Loop through all li elements of list, and make them drop targets
      var dl = dojo.byId("listToRearrange");
      var lis = dl.getElementsByTagName("li");
      for (var i=0; i<lis.length; i++)
         new dojo.dnd.HtmlDragSource(lis[i], "dest");

      new dojo.dnd.HtmlDropTarget(dl,"dest");
   }

   dojo.addOnLoad(initList);
</script>
</head>
<body>
<H1>Jimi Hendrix Albums</H1>
<p>Arrange in order of your own preference.</p>
<ul id="listToRearrange">
   <li>Electric Ladyland</li>
   <li>Are You Experienced?</li>
   <li>Axis, Bold as Love</li>
</ul>
</body>
</html>

Once this is done, you can use getElementsByTagName to loop through the elements in their new order, then send them by dojo.io or a page submission.