How to create dynamic templates for nodes based on node colors in an organizational chart
Code example
Visualizing hierarchical structures is more than just connecting nodes—it's about creating an intuitive and engaging experience. One way to enhance clarity and personality in an org chart is by using dynamic colors to differentiate roles or teams.
In this example, we use the OrgChart JS library to assign a custom background color to each node dynamically based on a property in the data.
Key Features:
Each person is represented by a node with a unique background color.
Templates are generated on the fly for any color used in the data.
Minimal configuration with support for interactive editing.
Here's the JavaScript code:
var chart = new OrgChart(document.getElementById("tree"), {
nodeMouseClick: OrgChart.action.edit,
mouseScrool: OrgChart.action.none,
nodeBinding: {
field_0: "name"
}
});
var nodes = [
{ id: "1", name: "Amber McKenzie", color: 'FFCA28' },
{ id: "2", pid: "1", name: "Ava Field", color: '039BE5' },
{ id: "3", pid: "1", name: "Peter Stevens", color: 'F57C00' }
];
function createTemaplate(name, color) {
var templateName = name + color;
OrgChart.templates[templateName] = Object.assign({}, OrgChart.templates.ana);
OrgChart.templates[templateName].node =
`<rect rx="5" x="0" y="0" height="120" width="250" fill="#${color}" stroke-width="1" stroke="black"></rect>`;
chart.config.tags[templateName] = {
template: templateName
};
}
for (var i = 0; i < nodes.length; i++) {
let color = nodes[i].color;
if (!OrgChart.templates['myTemplate' + color]) {
createTemaplate('myTemplate', color);
}
nodes[i].tags = ["myTemplate" + color];
};
chart.load(nodes);
Why This Works
Each node has a color
property that drives the creation of a unique OrgChart template. These templates are assigned using tags
, allowing the chart to render each node with its corresponding background.
This approach gives you flexibility to style org charts by departments, seniority, or any other meaningful attribute—on the fly.
Dynamic template - OrgChart JS