Objectives and outcomes

In this tutorial we are going to learn about sortable interaction in jqueryUI by the use of which we can sort html document elements.Example for the same is shown below:


  1. Item 1
  2. Item 5
  3. Item 6
  4. Item 4
  5. Item 2
  6. Item 3



We can sort objects by dragging them.



HTML code:

<html>
<head>
<title>jQuery UI Sortable</title>
<link href="jquery-ui.min.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
</head>
<body>
<ol id="sort1">
<li class="content">Item 1</li>
<li class="content">Item 5</li>
<li class="content">Item 6</li>
<li class="content">Item 4</li>
<li class="content">Item 2</li>
<li class="content">Item 3</li>
</ol>
</body>
</html>


CSS stylesheet

<style>
#sort1 
{ 
list-style-type: none;
margin: 0;
padding: 0;
}
#sort1 li 
{
padding: 0.4em;
padding-left: 1.5em; 
font-size: 18px; 
}
.content 
{
background: #585858;
border: 1px solid #FFF;
color: #FFF;
}
</style>




Javascript

<script>
$(function() {
$( "#sort1" ).sortable();
});
</script>


We have used jqueryUI inbuilt function sortable. In the next example we are going to use placeholder constraint with sortable function. Example for the same is shown below:



  1. Item 1
  2. Item 5
  3. Item 6
  4. Item 4
  5. Item 2
  6. Item 3



We can sort objects by dragging them.



HTML code:

<html>
<head>
<title>jQuery UI Sortable</title>
<link href="jquery-ui.min.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
</head>
<body>
<ol id="sort2">
<li class="content">Item 1</li>
<li class="content">Item 5</li>
<li class="content">Item 6</li>
<li class="content">Item 4</li>
<li class="content">Item 2</li>
<li class="content">Item 3</li>
</ol>
</body>
</html>


CSS stylesheet

<style>
#sort2 
{
list-style-type: none; 
margin: 0;
padding: 0;  
}
#sort2 li 
{
padding: 0.4em;
padding-left: 1.5em; 
font-size: 18px; 
}
.emptyli 
{
background-color: #000;
}
.content 
{
background: #585858;
border: 1px solid #FFF;
color: #FFF;
}
</style>


Javascript

<script>
$(function(){
$( "#sort2" ).sortable({
placeholder: "emptyli"
});
});
</script>


Now we have used the placeholder constraint with value emptyli which is a class declared in stylesheet. As soon as we drag an item a black color line is drawn which highlight the position of moving item.