Custom Aligning Nodes in a JavaScript Organizational Chart by changing X and Y
Creating a visually appealing and well-structured organizational chart can be a rewarding experience, especially when you have the flexibility to customize the alignment of nodes. In this blog post, we'll walk you through the process of custom aligning nodes using JavaScript. We'll use a simple example to demonstrate how you can achieve this with the OrgChart JS library.
Code example
Step-by-Step Guide
- Adding the Library and HTML Elements First, you need to include the OrgChart JS library and create a
div
element where the chart will be rendered.
<script src="https://cdn.balkan.app/orgchart.js"></script>
<div id="tree"></div>
- Loading the Data Next, we initialize the chart and load the data. This data defines the structure of our organizational chart, including the parent-child relationships between nodes.
let chart = new OrgChart(document.getElementById("tree"), {
mode: 'dark',
mouseScrool: OrgChart.none,
layout: OrgChart.treeLeftOffset,
nodeBinding: {
field_0: "id"
}
});
chart.load([
{ id: 1 },
{ id: 2, pid: 1 },
{ id: 3, pid: 2},
{ id: 4, pid: 2},
{ id: 5, pid: 2},
{ id: 6, pid: 2},
{ id: 7, pid: 1},
]);
- Custom Aligning Nodes To custom align nodes, we need to listen to the
prerender
event. This event allows us to manipulate the nodes before they are rendered on the screen. In our example, we'll align the y-coordinate of node 7 with node 6. Please note that you need to add the below code between the chart initialization and loading the data.
chart.on("prerender", function(sender, args){
let node1 = args.res.nodes[6];
let node2 = args.res.nodes[7];
node2.y = node1.y;
});
Explanation
- Adding the Library and HTML Elements: We include the OrgChart JS library and create a
div
element to render the chart.
- Data Loading: The
load
method is used to input the data that defines the organizational structure.
- Event Handling: By handling the
prerender
event, we gain access to the nodes before they are rendered. This allows us to modify their properties, such as the y-coordinate in this example.
Align nodes by change x and y - OrgChart JS
Conclusion
Custom aligning nodes in an organizational chart can greatly enhance the visual representation of your data. By following the steps outlined in this guide, you can easily manipulate node positions to suit your needs. Experiment with different alignments and settings to create the perfect chart for your organization.
Happy charting! 🎉