Introduction
This article explains how to reorder elements in a List using the mouse using jQuery.
What we are creating:
Now let's see the procedure required to create such an application.
Step 1
First of all I created an application in .NET.
In this application I created a List of some objects that will be reordered.
<body>
<ul id="sort_me">
<li >Item 1</li>
<li >Item 2</li>
<li >Item 3</li>
<li >Item 4</li>
<li >Item 5</li>
<li >Item 6</li>
<li >Item 7</li>
</ul>
</body>
The Id of this Unordered List is set to "sort_me".
Step 2
Now I will add some CSS Style to this Unordered List as in the following:
<style>
#sort_me { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sort_me li { margin: 0 3px 3px 3px; width:300px; border:solid 1px black; background-color:grey; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
#sort_me li span { position: absolute; margin-left: -1.3em; }
</style>
Step 3
Now for the main and final part of this application, in other words the jQuery part.
First of all you need to add the following two external jQuery files to your application:
- jQuery-ui-1.10.3.js
- jQuery-1.9.1.js
You can either download them from the jQuery Site or you can download the Zip file of this application provided at the start of the article and then fetch the jQuery files from it.
Now we will create JavaScript functions that will work on our application.
<script>
$(function () {
$("#sort_me").sortable();
$("#sort_me").disableSelection();
});
</script>
This small piece of code will solve our problem and will show a great result.
The complete code of our application is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="WebApplication45.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui-1.10.3.js"></script>
<style>
#sort_me { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sort_me li { margin: 0 3px 3px 3px; width:300px; border:solid 1px black; background-color:grey; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
#sort_me li span { position: absolute; margin-left: -1.3em; }
</style>
<script>
$(function () {
$("#sort_me").sortable();
$("#sort_me").disableSelection();
});
</script>
</head>
<body>
<ul id="sort_me">
<li >Item 1</li>
<li >Item 2</li>
<li >Item 3</li>
<li >Item 4</li>
<li >Item 5</li>
<li >Item 6</li>
<li >Item 7</li>
</ul>
</body>
</html>
Now our application is ready to be executed.
Output
First of all you will see an output window like this one:
Now you can reorder a list in any manner as you like.