Create Organizational Charts in JavaScript
Tags: javascript, webdev, productivity, tutorial
Published: 2019-06-12 10:45:40

---
title: Create Organizational Charts in JavaScript
published: true
description: This blog explains the creation and customization of the org (organizational) chart in a JavaScript application using Syncfusion Diagram control.
tags: 
canonical_url: https://www.syncfusion.com/blogs/post/create-organizational-charts-in-javascript.aspx
---

<a href="https://en.wikipedia.org/wiki/Organizational_chart">Org charts</a> are graphical representations of organizational structures. Their purpose is to illustrate the relationships and relative ranks of positions within an organization. An org chart may also be referred to as an <strong>organization chart</strong>, <strong>organizational chart</strong>, or <strong>hierarchy tree or chart</strong>.

Are you looking for a JavaScript library to create an <strong>org chart</strong> with less effort and which is very effective? Then you are in the right place, because the Syncfusion <a href="https://www.syncfusion.com/javascript-ui-controls/js-diagram"><strong>JavaScript Diagram Library</strong></a> helps you do that with easy configuration settings. In this blog, I will walk you through the steps involved in the creation of an org chart using the Syncfusion Diagram Library.
<h2>Getting Started with a Simple Org Chart</h2>
Let’s create a simple org chart as shown in the below image using the <a href="https://www.syncfusion.com/javascript-ui-controls/js-diagram">Syncfusion Diagram Library</a>. The Diagram control has a high-performing layout algorithm to arrange parent and children elements. It can load and lay out up to 1,000 nodes and 1,000 connectors in two to three seconds.

The Diagram control supports visualizing an org chart from the data source. This avoids having to manually feed data to individual nodes. The data source should be defined in JSON format and configured to the diagram.

<img class="size-full wp-image-39232 aligncenter" src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Org-Chart.png" alt="A Simple Org Chart" width="686" height="378" />
<ul>
 	<li>Please refer to our help <a href="https://ej2.syncfusion.com/documentation/diagram/getting-started/?no-cache=1">documentation</a> to learn more about the dependent scripts and theme files required to integrate the Diagram control in a JavaScript application.</li>
 	<li>Define the employee information as a JSON array</li>
 	<li>Create an instance of the Diagram control.</li>
 	<li>Configure the data to the <strong>dataSourceSettings</strong> property of the created diagram instance.</li>
 	<li>In the Diagram control, the rectangular boxes shown in the screenshot represent nodes, and lines represent connectors. The text inside the rectangular box represents annotations.</li>
 	<li>When each node is created, the <strong>dataSourceSettings</strong> <strong>doBinding</strong> method will trigger. You can use this method to configure the employee information inside the node.</li>
 	<li>Since all the nodes have the same width and height, you can define the common formatting for all nodes through the <strong>getNodeDefaults</strong> method. Likewise, you can define the common formatting properties for connectors through the <strong>getConnectorDefaults</strong> method.</li>
 	<li>After configuring the data source, define <strong>layout type</strong> to arrange the parent and child nodes positions automatically.</li>
</ul>
The code example below includes all the previously discussed steps. The full sample is available here: <a href="https://stackblitz.com/edit/1woeqw-u8dzc7">https://stackblitz.com/edit/1woeqw-u8dzc7</a>.
```javascript
import {data} from './datasource.js';

var items = new ej.data.DataManager(data);

var diagram = new ej.diagrams.Diagram({
    width: "1000px",
    height: "600px",
    dataSourceSettings: {
        // set the unique field from data source
        id: 'id', 
        // set the field which is used to identify the reporting person
        parentId: 'manager', 
        // define the employee data
        dataManager: items,
        doBinding: function (node, data) {
            // You will get the employee information in data argument and bind that value directly to node's built-in properties.
            node.annotations = [{ content: data.role }];
            node.style = { fill: data.color };
        }
    },
    layout: {
        // set the layout type
        type: 'OrganizationalChart'
    },
    // set the common settings for node and connector
    getNodeDefaults: nodeDefaults,
    getConnectorDefaults: connectorDefaults,
    // hide the gridlines in the diagram
    snapSettings: { constraints: ej.diagrams.SnapConstraints.None }
});
diagram.appendTo('#diagram');

function nodeDefaults(node) {
    node.annotations[0].style.color = "white";
    node.width = 120; 
    return node;
}

function connectorDefaults(connector) {
    connector.type = 'Orthogonal';
    connector.targetDecorator = { shape: 'None' };
    return connector;
}
```
<h2>Features &amp; Examples</h2>
<h3>Org Chart Shape Customization</h3>
You can easily create different types of org charts shapes and visualize them with custom UI design.

The <strong>setNodeTemplate</strong> method allows you to define a custom template for org chart. Please refer to the below code example for details.
```javascript
//Funtion to add the Template of the Node.
function setNodeTemplate(obj, diagram) {
    // create the stack panel
    var content = new ej.diagrams.StackPanel();
    content.id = obj.id + '_outerstack';
    content.orientation = 'Horizontal';
    content.style.strokeColor = 'gray';
    content.padding = { left: 5, right: 10, top: 5, bottom: 5 };
  
    // create the image element to map the image data from the data source
    var image = new ej.diagrams.ImageElement();
    image.id = obj.id + '_pic';
    image.width = 50; image.height = 50; image.style.strokeColor = 'none';
    image.source = obj.data.ImageUrl;
  
    // create the stack panel to append the text elements.
    var innerStack = new ej.diagrams.StackPanel();
    innerStack.style.strokeColor = 'none';
    innerStack.margin = { left: 5, right: 0, top: 0, bottom: 0 };
    innerStack.id = obj.id + '_innerstack';
  
    // create the text element to map the Name data from the data source
    var text = new ej.diagrams.TextElement();
    text.style.bold = true;
    text.id = obj.id + '_name';
    text.content = obj.data.Name;
  
    // create the text element to map the designation data from the data source
    var desigText = new ej.diagrams.TextElement();
    desigText.id = obj.id + '_desig';
    desigText.content = obj.data.Designation;
  
    // append the text elements
    innerStack.children = [text, desigText];
    
    // append the image and inner stack elements
    content.children = [image, innerStack];
    return content;
}
```
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Org-Chart-Customization.png" alt="Customized Org Chart" style="width:100%">
  <figcaption>Customized Org Chart</figcaption>
</figure>
The full sample code is available here: <a href="https://stackblitz.com/edit/1woeqw-5ahyy6">https://stackblitz.com/edit/1woeqw-5ahyy6</a>
<h3>Expand and Collapse</h3>
Use the <strong>expandIcon</strong> and <strong>collapseIcon</strong> properties of nodes to implement the expand and collapse features of the tree-shaped org chart. The following code example illustrates this.
```javascript
function nodeDefaults(node) {
  ….
  node.expandIcon = { shape: 'Minus' };
  node.collapseIcon = { shape: 'Plus' };
  return node;
}
```
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Expand-and-Collapse-Org-Chart.gif" alt="Expand and Collapse Org Chart" style="width:100%">
  <figcaption>Expand and Collapse Org Chart</figcaption>
</figure>
The full sample for this feature is available here: <a href="https://stackblitz.com/edit/1woeqw">https://stackblitz.com/edit/1woeqw</a>.
<h3>Drag-and-Drop (Editing Hierarchy Interactively)</h3>
You can easily modify the org chart interactively by dragging the child or parent nodes and dropping them at the desired locations. To enable editing of the hierarchical structure of the org chart, add the following code in the <strong>drop</strong> method of the Diagram control.
```javascript
var diagram = new ej.diagrams.Diagram({
    ...    
    // trigger the drop event to update the org chart structure when drag and drop the child node.
    drop: drop
  });

function drop(args) {
    if (args.target && args.target instanceof ej.diagrams.Node) {
        var connector = diagram.getObject(args.element.inEdges[0]);
        connector.sourceID = args.target.id;
        diagram.dataBind();
        diagram.doLayout();
        // update your local data source when modifying org chart structure.
        updateDataSource(args.element, args.target);
    }
}
  
function updateDataSource(source, target) {
    var updateData = data.find(function(element) {
        return element.id === source.data.id;
    });
    if(updateData) {
      updateData.manager = target.data.id;
    }
}
```
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Drag-and-Drop-Org-Chart.gif" alt="Drag and Drop nodes in Org Chart" style="width:100%">
  <figcaption>Drag and Drop nodes in Org Chart</figcaption>
</figure>
The full sample is available here: <a href="https://stackblitz.com/edit/1woeqw-a5dxag">https://stackblitz.com/edit/1woeqw-a5dxag</a>.
<h3>Assistants</h3>
The Diagram control supports defining assistants in the org chart. Assistants are child items that have a different relationship with the parent node. They are laid out in a dedicated part of the tree.

The layout’s <strong>getLayoutInfo</strong> method will be triggered when positioning each node on the layout, and it takes node and tree information as the arguments. Use this method to specify a node as an assistant node. Refer to the following code example for a demonstration.
```javascript
var diagram = new ej.diagrams.Diagram({
    ...
    layout: {
        type: 'OrganizationalChart',
        getLayoutInfo: function (node, options) {
            // you can get the children belongs to the parent node and decide the assistants from that children.
            if (node.data.role === 'General Manager') {
                options.assistants.push(options.children[2]);
                options.children.splice(2, 1);
            }
        }
    },    
});
```
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Assistants-Org-Chart.png" alt="Assistants in Org Chart" style="width:100%">
  <figcaption>Assistants in Org Chart</figcaption>
</figure>
The full sample is available here: <a href="https://stackblitz.com/edit/1woeqw-a81wbz">https://stackblitz.com/edit/1woeqw-a81wbz</a>.
<h3>Orientation &amp; Alignment</h3>
You can arrange the organizational chart with different orientations, such as top-to-bottom, left-to-right, right-to-left, and bottom-to-top as needed. Leaf-level nodes of the org chart can be aligned either horizontally or vertically. Nodes can be aligned to the left, right, or center horizontally and to the top, bottom, or middle vertically. You can customize the horizontal and vertical spacing between each level.

Please refer to the following code example to set the orientation and customize leaf-level node alignment.
```javascript
var diagram = new ej.diagrams.Diagram({
    ...
    layout: {
      type: 'OrganizationalChart',
      // set the layout orientation
      orientation: 'TopToBottom',
      // set the spacing between each level in horizontal and vertical direction
      horizontalSpacing: 50, verticalSpacing: 50,
      getLayoutInfo: function (node, options) {
          // set the leaf-level node alignment
          if (!options.hasSubTree) {
              options.orientation = 'Horizontal';
              options.type = 'Center';
          }
      }  
    },    
});
```
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/Orientation-Alignment-Org-Chart.png" alt="Orientation &amp; Alignment in Org Chart" style="width:100%">
  <figcaption>Orientation &amp; Alignment in Org Chart</figcaption>
</figure>
The full sample is available here: <a href="https://stackblitz.com/edit/1woeqw-o8njkk">https://stackblitz.com/edit/1woeqw-o8njkk</a>.
<h3>Zooming and Panning</h3>
Viewing a large org chart on a small screen can be quite difficult. Zooming and panning support helps to provide a better view of the chart.

Use Ctrl + mouse wheel operation to zoom in and out on the diagram. To activate zooming and panning support in the Diagram control, use the following code example.
```javascript
var diagram = new ej.diagrams.Diagram({
    // enable the pan tool
    tool: ej.diagrams.DiagramTools.ZoomPan
});
```
<figure>
  <img src="https://blog.syncfusion.com/wp-content/uploads/2019/05/zoom-and-pan.gif" alt="Zoom and pan org chart" style="width:100%">
  <figcaption>Zoom and pan org chart</figcaption>
</figure>
The full sample is available here: <a href="https://stackblitz.com/edit/a2qdyg">https://stackblitz.com/edit/a2qdyg</a>.
<h3>Exporting</h3>
You can easily export the diagram to different image formats such as PNG, JPEG, BMP, and SVG.

Please refer to the below code example and demo link to explore this feature.
```javascript
diagram.exportDiagram({format: 'PNG', fileName: 'OrgChart'});
```
The full sample is available here: <a href="https://stackblitz.com/edit/1woeqw-zcjbss">https://stackblitz.com/edit/1woeqw-zcjbss</a>.
<h3>Lazy Loading</h3>
Loading very large data sets in a diagram can be time-consuming. Use the lazy loading UI virtualization technique to load only the objects that lay on the viewport. This allows the diagram to load and display large data within a second.

To enable the virtualization feature, please use the following code example.
```javascript
var diagram = new ej.diagrams.Diagram({
    // enable virtualization
    constraints: ej.diagrams.DiagramConstraints.Default | ej.diagrams.DiagramConstraints.Virtualization,
});
diagram.appendTo('#diagram');
```
The full sample is available here: <a href="https://stackblitz.com/edit/hnqutl">https://stackblitz.com/edit/hnqutl</a>.
<h2>Conclusion</h2>
In this blog post, we have seen how to create and customize organizational charts using the Syncfusion JavaScript Diagram Library. If you would like to try the Diagram Library, you can download our <a href="https://www.syncfusion.com/downloads/essential-js2">free trial</a>. You can visit the Diagram Library source in <a href="https://github.com/syncfusion/ej2-javascript-ui-controls">GitHub </a>and check our <a href="https://ej2.syncfusion.com/demos/#/material/diagram/default-functionalities.html">live demo</a> and <a href="https://ej2.syncfusion.com/documentation/diagram/getting-started/?no-cache=1">documentation </a>for detailed explanations.

If you have any questions, please let us know in the comments section below. You can also contact us through our <a href="https://www.syncfusion.com/forums">support forum</a>, <a href="https://www.syncfusion.com/support/directtrac/incidents/">Direct-Trac</a>, or <a href="https://www.syncfusion.com/feedback/javascript">Feedback Portal</a>. We are always happy to assist you!

The post [Create Organizational Charts in JavaScript](https://www.syncfusion.com/blogs/post/create-organizational-charts-in-javascript.aspx) appeared first on [Syncfusion Blogs](https://www.syncfusion.com/blogs).