Wednesday 18 September 2013

Simple Drag and Drop Application using JQuery and HTML

Step1: Create a new Web Application

Step2: Add two unordered list, give them some unique ID and same class name


<table>
            <tr>
                <td valign="top">
                    <ul id="sort1" class="dragdrop">
                        <li>Item1 </li>
                        <li>Item2</li>
                    </ul>
                </td>
                <td valign="top">
                    <ul id="sort2" class="dragdrop">
                        
                    </ul>
                </td>
            </tr>
</table>

Id is used to apply styling to the list elements and class is used to enable drag-drop functionality on lists.

Step3: Now add an element to any of the list item. Apply some styling to list and list item using following code inside head tag


<style type="text/css">
        #sort1, #sort2     
        {
            list-style-type: none;
            padding: 10px;
            margin: 5px;
            width: 200px;
            background: #FFDAB9;
            vertical-align:top;
        }
        #sort1 li, #sort2 li            
       {
            border: 2px;
            padding: 5px;
            margin: 5px;
            background: #9ACD32;
            cursor: pointer;
            border-color: Black;
            width: 180px;
            text-align: center;
            vertical-align: middle;
        }
</style>

To enable the drag-drop functionality, add reference of the following java script files. These files are accessed from Google CDN.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js" type="text/javascript"></script>

The following java script code will enable drag-drop on list items.

<script type="text/javascript">
        $(function () {
            $("ul.dragdrop").sortable({  
                connectWith: "ul"
            });
        });
</script>

Here “drag drop” is the class which we have declared for the unordered list. The drag drop is used to identify the list element, on which we are applying “sortable” functionality so that the items inside list can be freely move from one list to another list or within the same list.
Now you can run the application in browser and try to drag Item2 from list1 and try to put it into list2. You can freely move one item into another list or in same list.

Thanks :)

No comments:

Post a Comment