Skip to content

Pin (set as root) a node in an OrgChart

If you are building interactive organizational charts with OrgChart JS, you may want to pin or fix a node as a root so it stays visible at the top of the visualization. This is especially useful in large structures where users need to focus on a specific department, person, or unit.

In this article, we will implement a Set As Root feature that lets users dynamically promote any node to root level.

Demo Setup

Start by including OrgChart JS and creating a container:

html
<script src="https://balkan.app/js/OrgChart.js"></script>
<div id="tree"></div>

Initialize the chart with a sample dataset:

javascript
let chart = new OrgChart(document.getElementById("tree"), {
    template: "olivia",
    mode: "dark",
    layout: OrgChart.tree,
    roots: [2, 3],
    nodeBinding: {
        field_0: "id",
        field_1: "pid"
    },
    nodes: [
        { id: 1 },
        { id: 2, pid: 1 },
        { id: 3, pid: 1 },
        { id: 4, pid: 1 },
        { id: 5, pid: 2 },
        { id: 6, pid: 2 },
        { id: 7, pid: 2 },
        { id: 8, pid: 3 },
        { id: 9, pid: 3 },
        { id: 10, pid: 3 },
        { id: 11, pid: 3 },
        { id: 12, pid: 3 },
        { id: 13, pid: 3 },
        { id: 14, pid: 4 },
        { id: 15, pid: 4 },
        { id: 16, pid: 4 }
    ]
});

Add "Set As Root" to the Node Menu

Use the built-in nodeMenu configuration to add a custom menu item:

javascript
nodeMenu: {
    root: {
        icon: "",
        text: "Set As Root",
        onClick: function (nodeId) {
            if (chart.config.roots.indexOf(nodeId) === -1) {
                chart.config.roots.push(nodeId);
                chart.draw();
            }
        }
    }
}

What this does:

  • Shows Set As Root in the node menu.
  • Adds the selected node ID to the roots array if it is not already there.
  • Redraws the chart so the new root is visible at top level.

Visual Behavior

Imagine node 1 is your top executive, while nodes 2 and 3 are department heads. With this setup, those nodes can stay visible as roots. Users can also promote another node such as 4 by right-clicking it and selecting Set As Root.

With just a few lines of code, you make large hierarchies easier to navigate and explore.