Another amazing effect provided by JQuery library is the ability to sort an object list on the fly by performing a drag and drop option. In this tutorial you will learn how easily you can build the sortable elements by using JQuery.
Firstly we need to import the following javascript libraries.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
Fo example, we will sort a list of div tag element. You can copy and paste the following code. Note: we include a textbox, so you can see the sorting values.
<div id="accordion"> <div class="group" id="divGroup1"> <div class="content">Section 1</div> </div> <div class="group" id="divGroup2"> <div class="content">Section 2</div> </div> <div class="group" id="divGroup3"> <div class="content">Section 3</div> </div> <div class="group" id="divGroup4"> <div class="content">Section 4</div> </div> </div> <input id="changevalues" type="text" value="" />
Next, we will create a function that will execute during the window load, it will look for a html tag named accordion and w
<script type="text/javascript"> $(function () { $("#accordion") .accordion({ header: "> div > div.content" }) .sortable({ axis: "y", handle: "div.content", update: function (event, ui) { getValues(); } }); }); function getValues() { var values = []; $('#accordion > .group').each(function (index) { values.push($(this).attr("id").replace("divGroup", "")); }); $('#changevalues').val(values); } </script>
We add some style to the list, so you can see the action easily.
<style type="text/css"> .group{ background:gray; color:#ffffff; margin:3px 0; cursor:pointer; width:200px; padding:10px; border-radius:5px; } .group:hover{ background:#9C3; } </style>
See the quick demo below.
Please see carefully the given value entered in the text box on the time you perform a sortable items.
Section 1
Section 2
Section 3
Section 4