This is a jquery ui sortable helper plugin for handy tree type structure sotable.

Overview

Tree Sortable

A drag and drop list item sorting and level changing library.

treeSortableBanner

Motivation

The jQuery-ui's sortable plugin allows us to sort items vertically or horizontally. But sometimes we need some items to make a child of another item and also need to sort a parent with all of the children items. This is the reason why I've created this library for managing the parent-children relationship of list items and fully by drag and drop.

Installation

Download the treeSortable.js and treeSortable.css files and add the treeSortable.js file before the </body> tag. Note that include the treeSortable.js file after jquery and the jquery-ui scripts. Include the treeSortable.css stylesheet in the head section. For reference see the index.html file.

Usage

Create a ul element with the ID tree. If you want to use other ID instead of tree then you have to update the design of treeSortable.css file or need to write your own stylesheet. Add a <script> tag after treeSortable.js script. You could add the HTML content for the branches inside the ul element, but I prefer to create an array of branches.

const data = [
	{
		id: 1,
		level: 1,
		parent_id: 0,
		title: 'Branch 1'
	},
	{
		id: 2,
		level: 2,
		parent_id: 1,
		title: 'Branch 2'
	},
	.
	.
	.
]

Make sure the data is in a perfect parent-child relationship. And level must be accurate.

After create an instance of the TreeSortable object and create the Tree Branch.

const sortable = new TreeSortable();

// Creating the branch contents.
const $content = data.map(sortable.createBranch);

// Append the content as children of the `#tree` ul element
$('#tree').html($content);

// Finally run the sortable functionalities.
sortable.run();

That's all. Your sortable tree is interactive. Now you can change the order of the tree branch and can change the level of the branch as well.

Change sortable options

You can change sortable options for farther customizations. For changing the options you need to update the sortable.options object before calling the sortable.run() function.

branchSelector: ".tree-branch", branchPathSelector: ".branch-path", dragHandlerSelector: ".branch-drag-handler", placeholderName: "sortable-placeholder", childrenBusSelector: ".children-bus", levelPrefix: "branch-level", maxLevel: 10,

Options

Option Default Description
treeSortable #tree The tree root ID selector. If you change the root selector then you have to update the CSS as per requirements.
branchSelector .tree-branch The tree branch class selector. This need to be applied at the li element of the tree.
branchPathSelector .branch-path The left side path indication element's class selector.
dragHandlerSelector .branch-drag-handler The drag element. This element is responsible for enabling the dragging features of the branch.
placeholderName sortable-placeholder The placeholder name. This is for jquery-ui sortable. Note that there is no dot(.) or hash(#). See the jquery-ui sortable library.
childrenBusSelector .children-bus The children bus selector. This element is responsible for carrying the children on sorting a parent element.
levelPrefix branch-level This prefix is added to the li element and create a level class. For example, for the level 1 branch the class would be .branch-level-1
maxLevel 10 The maximum level the tree could go. For example, if you set the maxLevel to 2 then the branch could have maximum .branch-level-2.
depth 30 The Depth of a child branch. If you change the depth then you have to update the CSS of the .branch-level-X classes. See the treeSortable.css for more references.

For updating the options you could do-

sortable.options = {
	...sortable.options,
	branchSelector: '#otherTree',
	branchPathSelector: '.other-path',
	maxLevel: 2,
	depth: 40
}

// Then run the sortable
sortable.run();

Event

After each reorder or level change an event is fired for further operations.

sortable.onSortCompleted(function(event, ui) {
	// here the `event` is the sortable event.
	// The `ui` is the jquery-ui's ui object.
	// You can use the `ui.item`, `ui.helper` and so on.
	// See https://api.jqueryui.com/sortable/
});

You can perform async operations here as well. make the callback function asynchronous in that case.

sortable.onSortCompleted(async function(event, ui) {
	await updateDatabaseAsync();
});

Add child, Add sibling, delete branch.

You can add child branch or a sibling branch. Also you can delete a branch recursively. There are some functions attached to the branch element. The sortable.createBranch(data) function come with few action buttons with the branch at the right hand side. The first one is for creating a new child branch, the next one for creating a new sibling branch and last one is for deleting a branch recursively.

You could attach click event to the respective buttons for adding child/sibling and/or deleting branch. Note that the events must need to be attached on the document and implement the event delegation.

$(document).on('click', '.add-child', function(event) {
	event.preventDefault();
	$(this).addChildBranch();
});

For adding sibling-

$(document).on('click', '.add-sibling', function(event) {
	event.preventDefault();
	$(this).addSiblingBranch();
});

For deleting branch-

$(document).on('click', '.add-sibling', function(event) {
	event.preventDefault();

	// You could check the user consent before deleting branch.
	const confirm = window.confirm('Are you sure to delete the branch?');
	
	if (!confirm) {
		return;
	}

	$(this).removeBranch();
});

Contribution

If you find any issues please raise issue on github. Also if you want to contribute the plugin then create a PR. You can also contact with me at [email protected].

You might also like...

This app helps manage a bookstore. It comes in handy when you need to manage a personal book store or library. Entirely built on es6.

This app helps manage a bookstore. It comes in handy when you need to manage a personal book store or library. Entirely built on es6.

Awesome Books A Microverse project on learnong javascript. Additional description about the project and its features. Built With HTML5 CSS3 Javascript

Apr 22, 2022

The app helps you to add todo items to your list, mark completed ones and also delete finished items. Its a handy tool for your day today activies. Check out the live demo.

The app helps you to add todo items to your list, mark completed ones and also delete finished items. Its a handy tool for your day today activies. Check out the live demo.

Todo List App The app helps you to add todo items to your list, mark completed ones and also delete finished items. Its a handy tool for your day toda

Apr 22, 2022

Adds a handy $parent magic property to your Alpine components.

✨ Help support the maintenance of this package by sponsoring me. Alpine $parent Access parent components using a handy $parent magic variable. This pa

Aug 29, 2022

A handy wrapper for the Web Notifications API

Notify.js A handy wrapper for using the Web Notifications API. Notify.js aims to simplify requesting user permission and associated Web Notification A

Dec 4, 2022

A handy-dandy JS shim to run OreUI files in your browser (to varying degrees of success.)

OreUIShim (C) Luminoso 2022 / MIT Licensed. Contributions Welcome! A small shim JS file to experiment with oreUI in the browser. How to use Prerequisi

Dec 8, 2022

Small PNG to WEBP converter, terminal based and handy for a frontend developer :D

Image Utils A small util i used while making antstack.com What does it do and how to use? It basically converts .png files to .webp Read about Webp he

Aug 24, 2022

A handy little app for copying & pasting images.

A handy little app for copying & pasting images.

PikPicPASTE A handy little app for copying & pasting images. Usage Click and drag the hamburger tile to move the toolbar Click the hamburger tile to s

Nov 1, 2022

🏗️ Figma Plugin for speeding up and ensure consistency in the structure of your Figma projects

🏗️ Figma Plugin for speeding up and ensure consistency in the structure of your Figma projects

🏗️ Codely Structurer Figma Plugin Figma Plugin for speeding up and ensure consistency in the structure of your Figma projects Stars are welcome 😊 👤

Dec 14, 2022

JqTree - Tree widget for jQuery

JqTree - Tree widget for jQuery

jqTree JqTree is a tree widget. Read more in the documentation. Features Create a tree from JSON data Drag and drop Works on ie9+, firefox, chrome and

Dec 22, 2022
Comments
  • onSortCompleted triggered for every list on page

    onSortCompleted triggered for every list on page

    If you use two (or more) sortables on one page and e.g. use this code.

    <ul id="tree1"></ul>
    <ul id="tree2"></ul>
    
    

    The Script looks like this.

    (document).ready(function () {
    
        const data1 = [
            { id: 1, parent_id: 0, title: 'Europe', level: 1 },
            { id: 2, parent_id: 1, title: 'Asia', level: 2 },
            { id: 3, parent_id: 1, title: 'Africa', level: 2 },
        ];
    
        const data2 = [
            { id: 1, parent_id: 0, title: 'Ohio', level: 1 },
            { id: 2, parent_id: 1, title: 'Texas', level: 2 },
            { id: 3, parent_id: 1, title: 'California', level: 2 },
        ];
    
        const sortable1 = new TreeSortable();
        const $tree1 = $('#tree1');
        const $content1 = data1.map(sortable1.createBranch);
        $tree1.html($content1);
    
        sortable1.options = {
            depth: 30,
            treeSelector: '#tree1',
            branchSelector: '.tree-branch',
            branchPathSelector: '.branch-path',
            dragHandlerSelector: '.branch-drag-handler',
            placeholderName: 'sortable-placeholder',
            childrenBusSelector: '.children-bus',
            levelPrefix: 'branch-level',
            maxLevel: 10,
            dataAttributes: {
                id: 'id',
                parent: 'parent',
                level: 'level'
            },
        }
    
        sortable1.run();
    
        sortable1.onSortCompleted(function(event, ui) {
            console.log('continents');
        });
    
        const sortable2 = new TreeSortable();
        const $tree2 = $('#tree2');
        const $content2 = data2.map(sortable2.createBranch);
        $tree2.html($content2);
    
        sortable2.options = {
            depth: 30,
            treeSelector: '#tree2',
            branchSelector: '.tree-branch',
            branchPathSelector: '.branch-path',
            dragHandlerSelector: '.branch-drag-handler',
            placeholderName: 'sortable-placeholder',
            childrenBusSelector: '.children-bus',
            levelPrefix: 'branch-level',
            maxLevel: 10,
            dataAttributes: {
                id: 'id',
                parent: 'parent',
                level: 'level'
            },
        }
    
        sortable2.run();
    
        sortable2.onSortCompleted(function(event, ui) {
            console.log( 'States');
        });
    });
    

    Both lists are shown, can be nested and sorted.

    When you complete sorting one of these lists all onSortCompleted() on that site are triggered. If you sort #tree2 only sortable2.onSortCompleted() should be triggered.

    opened by troyalpha 1
Owner
Sajeeb Ahamed
JavaScript, React, Next, react-query, redux, reselect, jQuery, CSS, emotion, PHP, Joomla, WordPress.
Sajeeb Ahamed
100% type-safe query builder for node-postgres :: Generated types, call any function, tree-shakable, implicit type casts, and more

⚠️ This library is currently in alpha. Contributors wanted! tusken Postgres client from a galaxy far, far away. your database is the source-of-truth f

alloc 54 Dec 29, 2022
Fancytree - JavaScript tree view / tree grid plugin with support for keyboard, inline editing, filtering, checkboxes, drag'n'drop, and lazy loading

Fancytree Fancytree (sequel of DynaTree 1.x) is a JavaScript tree view / tree grid plugin with support for keyboard, inline editing, filtering, checkb

Martin Wendt 2.6k Jan 9, 2023
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Um bot de suporte feito usando threads para o Discord, 100% customizável, feito em JavaScript e inspirado no Rio Helper do servidor Elixir Lab e na Loritta Helper do serivdor de suporte da Loritta.

Ticket Bot Um bot de suporte feito usando threads para o Discord, 100% customizável, feito em JavaScript e inspirado no Rio Helper do servidor Elixir

ADG 6 Dec 21, 2022
Universally Unique Lexicographically Sortable Identifier

Universally Unique Lexicographically Sortable Identifier UUID can be suboptimal for many uses-cases because: It isn't the most character efficient way

ULID 2.1k Jan 2, 2023
JustGage is a handy JavaScript plugin for generating and animating nice & clean dashboard gauges. It is based on Raphaël library for vector drawing.

JustGage JustGage is a handy JavaScript plugin for generating and animating nice & clean dashboard gauges. It is based on Raphaël library for vector d

Bojan Djuricic 1.8k Jan 3, 2023
Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Stratulat Alexandru 192 Jan 2, 2023
jQuery plugin to sorting lists also the tree structures.

jquery-sortable-lists jQuery plugin to sorting lists also the tree structures. $('#myList').sortableLists( options ); You can sort an items of html li

camo 208 Dec 13, 2022