Drag and Drop Reordering in Org Charts with Balkan OrgChart
Interactive org charts are a great way to visualize hierarchies—but what if you want to change the order of sibling nodes on the fly? In this quick guide, I’ll show you how to enable drag-and-drop reordering of nodes at the same level using the powerful OrgChart JS library.
The Setup
First, include the library and set up a container for the chart:
<script src="https://cdn.balkan.app/orgchart.js"></script>
<div id="tree"></div>
Then, configure the chart in JavaScript:
let chart = new OrgChart(document.getElementById("tree"), {
mode: 'dark',
enableDragDrop: true,
mouseScrool: OrgChart.none,
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
(and optionally pid
) values when they're on the same level:
chart.onDrop((args) => {
let dragData = chart.get(args.dragId);
let dropData = chart.get(args.dropId);
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; // prevent default behavior
}
});
Loading the Chart
Here’s a sample dataset with id
, pid
(parent ID), and order
for custom sorting:
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 }
]);
Live Demo
Try it out yourself here:
👉 View the live example on Balkan Code Playground
With just a few lines of code, you’ve made your org chart interactive and user-friendly. Users can now reorder nodes at the same level simply by dragging and dropping.
Happy coding!