DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Top 5 JavaScript Libraries to Create an Organizational Chart
  • Must-Know Pros and Cons of JavaScript Diagram Editors
  • How To Create a Network Graph Using JavaScript
  • How To Create a Resource Chart in JavaScript

Trending

  • Performance Optimization Techniques for Snowflake on AWS
  • AI’s Role in Everyday Development
  • Fixing Common Oracle Database Problems
  • Teradata Performance and Skew Prevention Tips
  1. DZone
  2. Data Engineering
  3. Data
  4. Create Organizational Charts in JavaScript

Create Organizational Charts in JavaScript

Show everyone who's boss with this easy-to-follow tutorial.

By 
Senthil Kumar M user avatar
Senthil Kumar M
·
Sep. 11, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
21.5K Views

Join the DZone community and get the full member experience.

Join For Free

worlds-best-boss-mug

"People say I am the best boss...I think this sums it up. I found it at Spencer gifts."

Org charts 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 organization chart, organizational chart, or hierarchy tree or chart.

In this blog, I will walk you through the steps involved in the creation of an org chart using the Syncfusion Diagram Library.

Getting Started With a Simple Org Chart

Let’s create a simple org chart like the one shown below. The Diagram control can load and lay out up to 1,000 nodes and 1,000 connectors in two to three seconds. The data source should be defined in JSON format and configured to the diagram.

A Simple Org Chart

A Simple Org Chart


  • Please refer to our help documentation to learn more about the dependent scripts and theme files required to integrate the Diagram control in a JavaScript application.
  • Define the employee information as a JSON array.
  • Create an instance of the Diagram control.
  • Configure the data to the dataSourceSettings property of the created diagram instance.
  • In the Diagram control, the rectangular boxes shown in the screenshot represent nodes, while lines represent connectors. The text inside the rectangular box represents annotations.
  • When each node is created, the dataSourceSettingsdoBinding method will trigger. You can use this method to configure the employee information inside the node.
  • Since all the nodes have the same width and height, you can define the common formatting for all nodes through the getNodeDefaults method. Likewise, you can define the common formatting properties for connectors through the getConnectorDefaults method.
  • After configuring the data source, define the layout type to arrange the parent and child nodes positions automatically.

The code example below includes all the previously discussed steps. The full sample is available here.

import{data} from './datasource.js';

var items = newej.data.DataManager(data);

var diagram = newej.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 
    datadataManager: 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 
    typetype: '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' };
  returnnconnector;
}


Features and Examples

Org Chart Shape Customization

You can easily create different types of org charts shapes and visualize them with custom UI design.

The setNodeTemplate method allows you to define a custom template for org chart. Please refer to the below code example for details.

//Funtion to add the Template of the Node.
function setNodeTemplate(obj, diagram) {
  // create the stack panel
  var content = newej.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 = newej.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 = newej.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 = newej.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 = newej.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];returncontent;
}


Beginning org chart

Beginning org chart

The full sample code is available here.

Expand and Collapse

Use the expandIcon and collapseIcon properties of nodes to implement the expand and collapse features of the tree-shaped org chart. The following code example illustrates this.

function nodeDefaults(node) {
  ….
  node.expandIcon = { shape: 'Minus'};
  node.collapseIcon = { shape: 'Plus'};
  return node;
}


Expand and Collapse Org Chart

Expand and Collapse Org Chart

The full sample for this feature is available here.

Drag-and-Drop (Editing Hierarchy Interactively)

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 drop method of the Diagram control.

var diagram = newej.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 instanceofej.diagrams.Node) {
    varconnector = 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);
  }
}

functionupdateDataSource(source, target) {
  varupdateData = data.find(function(element) {
    return element.id === source.data.id;
  });
  if(updateData) {
    updateData.manager = target.data.id;
  }
}


Drag and Drop nodes in Org Chart

Drag and Drop nodes in Org Chart

The full sample is available here.

Assistants

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 getLayoutInfo 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.

var diagram = newej.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);
      }
    }
  },
});


Assistants in Org Chart

Assistants in Org Chart

The full sample is available here.

Orientation and Alignment

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.

var diagram = newej.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';
      }
    }
  },
});

Orientation & Alignment in Org Chart

Orientation & Alignment in Org Chart

The full sample is available here.

Zooming and Panning

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.

var diagram = newej.diagrams.Diagram({
  // enable the pan tool
  tool: ej.diagrams.DiagramTools.ZoomPan
});


Zoom and pan org chart

Zoom and pan org chart

The full sample is available here.

Exporting

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.

diagram.exportDiagram({
  format: 'PNG', 
  fileName: 'OrgChart'
});


The full sample is available here.

Lazy Loading

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.

var diagram = newej.diagrams.Diagram({
  // enable virtualization
  constraints: ej.diagrams.DiagramConstraints.Default | ej.diagrams.DiagramConstraints.Virtualization,
});
diagram.appendTo('#diagram');


The full sample is available here.

Conclusion

In this blog post, we have seen how to create and customize organizational charts using the Syncfusion JavaScript Diagram Library. You can visit the Diagram Library source in GitHub and documentation for detailed explanations.


Related Articles

  • Getting Started With Regraph — The Graph Visualization Toolkit for React.
Chart Diagram JavaScript

Published at DZone with permission of Senthil Kumar M. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Top 5 JavaScript Libraries to Create an Organizational Chart
  • Must-Know Pros and Cons of JavaScript Diagram Editors
  • How To Create a Network Graph Using JavaScript
  • How To Create a Resource Chart in JavaScript

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!