By using jQuery you can create drag and drop functionality as seen on iGoogle and Facebook with "only one line of code". To do this you need jQuery and jQuery UI.
The code:
$('#MyContainer').sortable();
There. You are done. This will enable you to drag, drop and sort all elements in the element MyContainer.
You can also add options and events to the sortable method. Here's a more advanced example where we have three articles that should be sortable and an event that runs when the list is updated.
<div id="articles">
<div id="article1" class="article">
<h2>Lorem ipsum</h2>
<p >Lorem ipsum ei eam esse molestiae maiestatis, eum te zzril congue. Mei ex autem persius, pro facer aperiri ornatus ad.</p >
</div>
<div id="article2" class="article">
<h2>Agam labore imperdiet</h2>
<p >Agam labore imperdiet nam cu, no pro error pertinax. Aliquip habemus pri id, an latine viderer inciderint qui.</p >
</div>
<div id="article3" class="article">
<h2>Reque suavitate no nec</h2>
<p >Reque suavitate no nec, vel ad choro aperiam pertinacia. Mei euismod utroque facilisis ea, et illud phaedrum senserit cum.
</p >
</div>
</div>
$(document).ready(function() {
$('#articles').sortable(
{
items: '.article',
// the type of element to drag
handle: 'h2',
// the element that should start the drag event
opacity: 0.9,
// opacity of the element while draging
placeholder: 'placeholder',
// class of the element displaying areas to move the element to
scroll:
false,
// don't scroll the page while draging
update: function(
event, ui) {
var articles = $('.article');
// select the list of articles
var newPosition = articles.index(ui.item);
// get the items new position in the article list
alert(ui.item.attr('id') + ' was moved to position ' + (newPosition + 1));
// alert the item that was moved and the new position
}
// event to run when the order of the elemnts is updated
}
);
});
Items specify which items should be draggable (in this case all elements with the class article). Handle sets the element that starts the drag event (the h2 element of the article). Opacity sets the elements opacity while dragging. Placeholder is the CSS class name of the element displaying the area to move the item to. Scroll specifies if the page should scroll while dragging. Update is the event called when an item has been moved and the DOM tree has been updated.
More on sortable.