JQuery - Nested Sortable

I was searching the web for a solution to use jQuery UI sortable to create a nested sortable list. Most of the scripts that i found had still some issues. so i created one of my own.

I started tot create a widget, but i couldn't find a good solution. So i tried to modify the sortable class itself. For now i think the result is acceptable. (see demo below).

Example 1

  1. Home
  2. Products
    1. Category 1
    2. Category 2
    3. product 1 of Category 1
      1. About us
  3. product 2 of Category 1

How it works?

Drag the helper over an item, if the left size from the helper is inside the item you create a child, if it's on the left of the item you add it to the same level.

The code

Here is the adapted class : ui.nestedSortable.js

the only difference is that there is an extra option 'nested' you can use. standaard the nested option is false, but you can set it to 'ul' or 'ol' (is there someone who knows how how to auto create a div tag if the value you enter is a classname or id?)

I do not work with connected sortables, everything is in the same sortable list.

This is my jQuery code for the sortable:

	$(document).ready(function(){
		$('#demo1').sortable({
			'tolerance':'intersect',
			'cursor':'pointer',
			'items':'li',
			'placeholder':'placeholder',
			'nested':'ol'
		})
	});

serialize and toArray:

I adapted the serialization of the tree to a readable string where each neste element is an array with the name "item_[ID]". It looks like this:

item[]=1&item[]=221&item_221[]=21&item_221[]=2&item_221[]=211&item[]=22

Also you can call the toArray function of the old sortable. You gets a nested Array where the first element is always the ID from the listItem and a second element is a new array with all his child elements.

Example 2

  • Home
  • Products
    • Category 1
      • product 1 of Category 1
      • product 2 of Category 1
    • Category 2
  • About us

maxLevels and maxItems

I added also 2 options for restrict the creation of levels and for each level the count of elements. The default value for maxLevel is 100.

maxItems is default an empty array, you can set a max number of itemsfor each level.

The cursor changes to "not-allowed" if you drag over a place that is not possible.

Example 3

  • Home
  • Products
    • Category 1
      • product 1 of Category 1
      • product 2 of Category 1
    • Category 2
  • About us

 

	$(document).ready(function(){
		$('#demo1').sortable({,
			'items':'li',
			'placeholder':'placeholder2',
			'nested':'ul'
			'maxlevels':3,
			'maxItems':[5,3,2]
		})
	});

Todo