Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Drag and drop sortable list using Mootools

To create a sortable list you will need http://webcodingeasy.com/js/mootools.js javascript library in your <head> tags.

Then you can use this simple list (attribute alt is the identifier)

<ul id='list'>
<li alt='1'>item1</li>
<li alt='2'>item2</li>
<li alt='3'>item3</li>
<li alt='4'>item4</li>
<li alt='5'>item5</li>
</ul>
<input type='hidden' name='sort_order' id='sort_order'/>

Then make it able to drag and drop while maintaining the order of identifiers and call ajax function on drop to save the sequence

<script type="text/javascript">
    /* when the DOM is ready */
    window.addEvent('domready', function() {
        /* create sortables */
        var sb = new Sortables('list', {
            /* set options */
            clone:true,
            revert: true,
            /* initialization stuff here */
            initialize: function() { 
                var sort_order = '';
                $$('#list li').each(function(li) 
                {
                    sort_order = sort_order +  li.get('alt')  + '|'; });
                    $('sort_order').value = sort_order;
            },
            /* once an item is selected */
            onStart: function(el) { 
                el.setStyle('background','#add8e6');
            },
            /* when a drag is complete */
            onComplete: function(el) {
                el.setStyle('background','#ddd');
                //build a string of the order
                var sort_order = '';
                $$('#list li').each(function(li) 
                { 
                    sort_order = sort_order +  li.get('alt')  + '|'; });
                if($('sort_order').value != sort_order)
                {
                    $('sort_order').value = sort_order;
                    var req = new Request({
                        url:'<?php echo $_SERVER['PHP_SELF']; ?>',
                        method:'post',
                        autoCancel:true,
                        data:'sort_order=' + sort_order,
                        onRequest: function() {
                        },
                        onSuccess: function() {
                            el.setStyle('background','#e9e9e9');
                        }
                    }).send();
                }
            }
        });
    });
</script>

Put this PHP code on the same page to save new sequence in database on ajax request

<?php
if(isset($_POST['sort_order']))
{
    $sort = explode("|", $_POST['sort_order']);
    for($i = 0; $i < (count($sort)-1); $i++)
    {
        //update database
        update("table", "order='".($i+1)."'", "where ID='".$sort[$i]."'");
    }
}
?>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus