Change The Order by Drag and Drop
Interactive org charts are a great way to visualize hierarchies, but sometimes you also need to reorder sibling nodes on the fly. In this quick guide, you will learn how to enable drag-and-drop reordering for nodes on the same level with OrgChart JS.
The Setup
First, include the library and create a container for the chart:
html
<script src="https://balkan.app/js/OrgChart.js"></script>
<div id="tree"></div>Then configure the chart in JavaScript:
javascript
let chart = new OrgChart(document.getElementById("tree"), {
enableDragDrop: true,
nodeBinding: {
field_0: "id",
field_1: "pid",
},
orderBy: 'order'
});Implementing Reordering Logic
To change the order of sibling nodes, listen for the onDrop event and swap their order values (and optionally pid) when both nodes are on the same level:
javascript
chart.onDrop((args) => {
let dragData = chart.get(args.dragId);
let dropData = chart.get(args.dropId);
if (dropData != undefined) {
let dragNode = chart.getNode(args.dragId);
let dropNode = chart.getNode(args.dropId);
if (dragNode.level == dropNode.level){
let temp = dropData.order;
dropData.order = dragData.order;
dragData.order = temp;
temp = dropData.pid;
dropData.pid = dragData.pid;
dragData.pid = temp;
chart.update(dropData).update(dragData).draw();
return false;
}
}
});Loading the Chart
Here is a sample dataset with id, pid (parent ID), and order for custom sorting:
javascript
chart.load([
{ id: 1, order: 1 },
{ id: 2, pid: 1, order: 2 },
{ id: 3, pid: 1, order: 3 },
{ id: 4, pid: 2, order: 4 },
{ id: 5, pid: 2, order: 5 },
{ id: 6, pid: 3, order: 6 },
{ id: 7, pid: 3, order: 7 }
]);With just a few lines of code, you can make your org chart more interactive and user-friendly by allowing users to reorder same-level nodes with drag and drop.