DnD Drag-N-Drop Javascript simplified

Have you ever wanted to implement drag-n-drop in your website?  Sounds great but looks difficult?  Well,  I have found a wonderful javascript library called Scriptaculous that makes it a breeze.

It is a simple as adding the script include tags in your head section ( luckily google has decided to host prototype and scriptaculous)

<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6/prototype.js" type="text/javascript src="></script>
<script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8/scriptaculous.js" type="text/javascript src="></script>

Then in your javascript create an instance of a Draggable.
new Draggable( 'id-element-to-drag' );

Thats right, thats all there is too it.

Scriptaculous supports much more than that.  With scriptaculous I can make a sortable list that is drag-n-drop enabled.  This is called a Sortable.   The biggest difference between a Dragable and a Sortable is that the Sortable operates on all of the child elements of a given element.  It basicly creates a bunch of Dragable instances for you.  The Sortable class also allows you save the current sort order and reload it later.  The Sortable class has a couple of requirements though or you will find yourself wondering why is it not working the way it should (or at least I did).

  1. The id of the elements have to have a delimiter that matches a RegEx used by the Sortable.  I always use xx_#  and it works great.
  2. The elements you are sorting have to be block level elements.  The exception to this is that table, tbody, and thead don’t work.

Lets suppose you have the following markup:

<div id='page1' class='currentPage'>
    <div id='item_0' class='item'>This is item 1</div>
    <div id='item_1' class='item'>This is item 2</div>
    <div id='item_2' class='item'>This is item 3</div>
</div>

The javascript to allow you to drag-n-drop the items in the list

Sortable.create( $('page1'), {tag: 'div', scroll: window} );

That’s it!  Notice I used the helper method Sortable.create this time so I didn’t have to worry about all of the options available to the Sortable class.  I also used the option scroll: window this says to scroll the window if I drag to the edge of the window.

I have only touched the surface of the power and ease of use that scriptaculous affords you.

[poll id=”3″]

Comments 2

  • Hi
    i need to automative scroll div when drag and drop table cell using javascript.

  • If you are using scriptaculous just set the scroll option when you create the Draggable to the container that you want to scroll.

Leave a Reply