1 minute reading time (219 words)

Sorting Nested List using jQuery

Hello!

This is informative Blog for Sorting Nested List using jQuery

If you want to sort elements of UL/LI in another UL/LI using drag and drop, Here is a quick guide to achieve that.

Here is the basic html for nested list:

<div  class="div-containing-list" >
	<ul id="main-list" class="main-list">
		<li id="sortable1" class="connectedSortable"><span>Item 1</span>
			<ul class="internal-list ui-state-default">
				<li class="">lesson1</li>
				<li class="">lesson2</li>
				<li class="">lesson3</li>
			</ul>
		</li>
		<li id="sortable2" class="connectedSortable"><span>Item 2</span>
			<ul class="internal-list ui-state-default">
				<li class="">lesson4</li>
				<li class="">lesson5</li>
			</ul>
		</li>
	</ul>
</div>

jQuery needed to achieve the drag and drop functionality

<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">

<script>

	$(function() {

		//use for sorting and accordion
		$( "#main-list .internal-list" ).sortable();
		$( "#main-list .internal-list" ).disableSelection();
		$( "#main-list" ).accordion();
                collapsible: true

		var $tab_items = $( "#main-list li" ).droppable({
			accept: ".connectedSortable li",
			hoverClass: "ui-state-hover",
			drop: function( event, ui ) {

				var $item = $( this );
				var $list = $($item.find(".internal-list" ));
				ui.draggable.hide( "slow", function() {

					$( this ).appendTo( $list ).show( "slow" );
					$("#main-list").accordion({ collapsible: true, active: false });
					$( $list ).parent().accordion();
				});
			}
		});
	});

</script>

The output for the list is as below. Her you can drag and drop each element in the list. Chapter can be drag and drop from Section 1 to Section2 and vise versa.

This is how it looks:

Before:

:b2ap3_thumbnail_Screenshot-from-2014-06-17-17_10_14.png

After:

b2ap3_thumbnail_Screenshot-from-2014-06-17-17_10_41.png

Hope this blog will be help!

0
Clone html element using jquery
Add automatic updates to your extensions with Akee...