OrgChart: Interactive Organization Chart in Vanilla JavaScript
| File Size: | 1.36 MB |
|---|---|
| Views Total: | 141841 |
| Last Update: | |
| Publish Date: | |
| Official Website: | Go to website |
| License: | MIT |
OrgChart is a vanilla JavaScript library for building interactive organization charts and family trees from nested JSON data or HTML lists. It also accepts flat parent_id records, with drag-and-drop editing and expandable branches.
Features:
- Renders nested JSON hierarchies, flat
parent_idrecords, or nested<ul>markup. - Expands and collapses branches with CSS transitions.
- Places charts in top-to-bottom, bottom-to-top, left-to-right, or right-to-left layouts.
- Supports pan, mouse-wheel zoom, and minimap navigation.
- Reorders hierarchy nodes through drag and drop.
- Adds, removes, and reorganizes nodes at runtime.
- Retrieves edited charts as nested hierarchies or flat records through
getHierarchy()andgetFlatDatasource(). - Exports charts to PNG or PDF.
- Supports custom node markup and custom icon sets.
- Uses compact and hybrid layouts for dense hierarchies.
- Builds family trees from grouped hierarchy data, with expandable and collapsible family branches.
- Supports touch interaction on mobile devices.
Use Cases:
- Map reporting lines inside an HR dashboard and let administrators reorganize teams through drag and drop.
- Build an employee directory with custom node cards, collapsed departments, and several hierarchy levels.
- Display a genealogy or pedigree tree with spouses, children, and custom family attributes.
- Trace reporting relationships across a large organization with multiple management levels.
Installation:
# npm npm install orgchart # Legacy Bower installation bower install orgchart
How to use OrgChart:
Basic usage:
Load the core stylesheet and JavaScript files in your document.
<link rel="stylesheet" href="dist/css/orgchart.css"> <script src="dist/js/orgchart.js"></script>
<div id="company-org-chart"></div>
Pass the employee hierarchy to new OrgChart(). The chartContainer selector matches the container above, and nodeContent: 'title' displays job titles beneath employee names.
var companyData = {
id: 'chief-executive',
name: 'Maya Chen',
title: 'Chief Executive Officer',
children: [
{
id: 'product-team',
name: 'Jordan Lee',
title: 'VP of Product',
children: [
{
id: 'product-design',
name: 'Avery Brooks',
title: 'Design Director'
},
{
id: 'product-research',
name: 'Morgan Ellis',
title: 'Research Lead'
}
]
},
{
id: 'engineering-team',
name: 'Sam Rivera',
title: 'VP of Engineering',
children: [
{
id: 'web-platform',
name: 'Taylor Kim',
title: 'Web Platform Lead'
}
]
}
]
};
var orgChart = new OrgChart({
chartContainer: '#company-org-chart',
data: companyData,
nodeContent: 'title',
visibleLevel: 3
});
Flat Data Source With parent_id
Pass database-style records directly as a flat array. Each parent_id references another row's id; one row must have a null or omitted parent.
<div id="flat-org-chart"></div>
var teamRows = [
{ id: 1, name: 'Company', parent_id: null },
{ id: 2, name: 'Engineering', parent_id: 1 },
{ id: 3, name: 'Design', parent_id: 1 },
{ id: 4, name: 'Frontend', parent_id: 2 }
];
var flatOrgChart = new OrgChart({
chartContainer: '#flat-org-chart',
data: teamRows,
pan: true,
zoom: true
});
OrgChart Data Structure
Node data defines IDs, display fields, CSS classes, and expansion state. OrgChart derives parent and sibling relationships from the loaded hierarchy.
id: Identifies each node for editing and hierarchy export. Use unique values.children: Contains nested descendant data.parent_id: Identifies the parent in a flat data source; usenullor omit it for the root.collapsed: Hides a node's descendants initially when set totrue.className: Adds custom CSS classes to the rendered node.hybrid: Arranges descendants vertically when the value is truthy.compact: Uses a compact layout for the node's descendants when truthy.outsider: Marks an outside member in family-tree data.
var departmentData = {
id: 'operations',
name: 'Operations',
title: 'Department',
className: 'department-node',
collapsed: false,
children: [
{
id: 'facilities',
name: 'Facilities',
title: 'Team'
},
{
id: 'procurement',
name: 'Procurement',
title: 'Team'
}
]
};
OrgChart Options
Data And Navigation Options
data(Object, Array, orHTMLUListElement, required): Accepts a nested JSON tree, flatparent_idrows, grouped family data, or an HTML list.pan(Boolean, defaultfalse): Lets users move the chart by dragging the chart area.zoom(Boolean, defaultfalse): Activates mouse-wheel zoom.minimap(Boolean, defaultfalse): Adds an overview navigator for large charts.zoominLimit(Number, default7): Sets the maximum zoom-in scale.zoomoutLimit(Number, default0.5): Sets the minimum zoom-out scale.visibleLevel(Nonnegative Integer or Boolean, default999): Sets initial expansion depth.falseshows the first level;0hides all initial nodes.
Layout Options
direction(String, default"t2b"): Sets chart direction. Supported values aret2b,b2t,l2r, andr2l.verticalLevel(Integer, minimum2): Starts vertical child alignment from a specified hierarchy level.toggleSiblingsResp(Boolean, defaultfalse): Adds separate controls for showing or hiding left and right siblings.chartClass(String, default""): Adds a custom class to the chart. This helps distinguish several OrgChart instances on one page.compact(Boolean or Function): Settrueto compact every branch, or pass a function that selects nodes for compact layout. Node-levelcompactvalues are also supported.
Node Content Options
nodeTitle(String, default"name"): Selects the data property used for the main node title.nodeContent(String): Selects the data property used for the secondary content area.nodeId(String, default"id"): Selects the data property used as each node's unique identifier.nodeTemplate(Function): Returns custom HTML for each node. Sanitize dynamic markup before returning it.createNode(Function): Receives the rendered node element and its data after node creation.
<div id="employee-chart"></div>
var employeeChart = new OrgChart({
chartContainer: '#employee-chart',
data: companyData,
nodeContent: 'title',
createNode: function(node, data) {
if (data.title) {
node.setAttribute('data-job-title', data.title);
}
}
});
Drag And Drop Options
draggable(Boolean, defaultfalse): Activates node drag and drop.dropCriteria(Function): ReceivesdraggedNode,dragZone, anddropZone. Return a Boolean value to accept or reject the relationship change.
<div id="editable-org-chart"></div>
var editableChart = new OrgChart({
chartContainer: '#editable-org-chart',
data: companyData,
draggable: true,
dropCriteria: function(draggedNode, dragZone, dropZone) {
return draggedNode.id !== 'engineering-team';
}
});
Export Options
PNG and PDF export use html2canvas, and PDF also requires jsPDF. When loading OrgChart directly in the browser, load the browser builds of those libraries before exporting.
exportButton(Boolean, defaultfalse): Adds the built-in export button.exportButtonName(String, default"Export"): Sets the export button label.exportFilename(String, default"OrgChart"): Sets the downloaded file name.exportFileextension(String, default"png"): Selectspngorpdf.exportScale(Number, default2): Sets the render scale used during chart export.
Lifecycle And Icon Options
initCompleted(Function): Runs after the chart finishes its initial render. It receives the rendered chart element.icons(Object): Replaces the built-in icon class map. You can use another icon library such as Font Awesome.
Load the icon pack's CSS before using its class names.
<div id="icon-chart"></div>
var iconChart = new OrgChart({
chartContainer: '#icon-chart',
data: companyData,
icons: {
theme: 'fa-solid fa-sm',
parentNode: 'fa-user-tie',
expandToUp: 'fa-angles-up',
collapseToDown: 'fa-angles-down',
collapseToLeft: 'fa-angles-left',
expandToRight: 'fa-angles-right',
collapsed: 'fa-circle-plus',
expanded: 'fa-circle-minus'
}
});
Customize Chart CSS
OrgChart exposes CSS variables for node dimensions, connector colors, hover states, and branch transitions.
.orgchart {
--oc-node-width: 180px;
--oc-line-color: #777;
--oc-duration: 250ms;
}
OrgChart API Methods
The instance properties chartContainer and chart reference its native container and rendered chart elements.
Initialization And Runtime Options
orgChart.init(options): Rebuilds the chart with updated options or data. It returns the OrgChart instance.orgChart.setOptions(options): Updates a partial set of settings. Navigation and export settings update in place; data, layout, and node-rendering changes rebuild the chart. Returns the OrgChart instance.orgChart.setOptions(name, value): Updates a single option by name, including navigation and export settings. Returns the OrgChart instance.orgChart.destroy(): Removes generated chart resources, releases listeners, and restores managed container styles. Returns the instance.
orgChart.setOptions('minimap', true);
orgChart.setOptions({
pan: true,
zoom: true
});
orgChart.init({
data: departmentData
});
Minimap Methods
Use setOptions('minimap', true) or setOptions('minimap', false) for UI toggles to keep the option value synchronized with the navigator.
orgChart.attachMinimap(): Creates the minimap for the current chart.orgChart.detachMinimap(): Removes the minimap.orgChart.updateMinimap(forceRefresh): Recalculates minimap state. Passtrueto redraw its node preview.
Hierarchy Editing Methods
For on-demand loading, handle the request in your application and insert the returned nodes through addAncestors(), addDescendants(), or addChildren().
orgChart.addAncestors(data, parentId): Adds ancestor data above the current hierarchy and attaches the existing root toparentId.orgChart.addDescendants(data, parent): Adds descendant data beneath a native parent node element.orgChart.addParent(currentRoot, data): Wraps the current root with a new parent node.orgChart.addSiblings(node, data): Adds sibling nodes beside a native node element.orgChart.addChildren(node, data): Adds child nodes beneath a native node element.orgChart.removeNodes(node): Removes a node and its descendants.
var engineeringNode = document.getElementById('engineering-team');
orgChart.addChildren(engineeringNode, [
{
id: 'quality-engineering',
name: 'Quality Engineering',
title: 'Team'
}
]);
Hierarchy Query Methods
orgChart.getHierarchy(includeNodeData): Returns the hierarchy. Passtrueto include node data along with IDs and children.orgChart.getFlatDatasource(): Returns the current hierarchy as flat records, recalculatingparent_idfor each loaded node, including hidden descendants.orgChart.getNodeState(node, relation): Returns{ exist, visible }forparent,children, orsiblings.orgChart.getParent(node): Returns the direct parent node ornull.orgChart.getChildren(node): Returns an array of direct child node elements.orgChart.getSiblings(node): Returns an array of direct sibling node elements.orgChart.getRelatedNodes(node, relation): Queriesparent,children, orsiblingsthrough one generalized method.
var productNode = document.getElementById('product-team');
var children = orgChart.getChildren(productNode);
var parent = orgChart.getParent(productNode);
var state = orgChart.getNodeState(productNode, 'children');
console.log(children);
console.log(parent);
console.log(state);
console.log(orgChart.getFlatDatasource());
Branch Visibility Methods
orgChart.hideParent(node): Hides a node's parent and the related sibling branch.orgChart.showParent(node): Reveals the parent branch.orgChart.hideChildren(node): Hides direct child branches.orgChart.showChildren(node): Reveals child branches.orgChart.hideSiblings(node, direction): Hides siblings. Setdirectiontoleftorright, or omit it for both sides.orgChart.showSiblings(node, direction): Reveals siblings on one side or both sides.
Zoom Method
orgChart.setChartScale(chart, multiplier, zoomAnchor): Changes chart scale within the configured zoom limits.zoomAnchoraccepts viewport coordinates in the form{ x, y }.
orgChart.setChartScale(orgChart.chart, 1.2, {
x: window.innerWidth / 2,
y: window.innerHeight / 2
});
Export Methods
orgChart.export(filename, extension): Downloads a PNG or PDF and returns a Promise resolving to its rendered canvas. Returnsfalsewhen export cannot begin; rejects the Promise and dispatchesexport-error.orgcharton failure.orgChart.exportPNG(canvas, filename): Downloads a prepared canvas as PNG.orgChart.exportPDF(canvas, filename, exportScale): Downloads a prepared canvas as PDF.
var result = orgChart.export('engineering-structure', 'png');
if (result) {
result.catch(function(error) {
console.error('Chart export failed:', error);
});
}
OrgChart Events
nodedrop.orgchart
Fires before a node moves. Read draggedNode, dragZone, and dropZone from event.detail. Call event.preventDefault() to cancel the drop.
orgChart.chart.addEventListener('nodedrop.orgchart', function(event) {
var detail = event.detail;
console.log('Dragged node:', detail.draggedNode);
console.log('Drop target:', detail.dropZone);
});
otherdropped.orgchart
Fires when an external draggable item is dropped onto a chart node. event.detail contains draggedItem and dropZone.
init.orgchart
Fires when the chart finishes rendering. To catch the first render, register a listener on its container before initialization.
<div id="event-org-chart"></div>
var eventContainer = document.getElementById('event-org-chart');
eventContainer.addEventListener('init.orgchart', function(event) {
console.log('Chart initialized:', event.target);
});
var eventChart = new OrgChart({
chartContainer: '#event-org-chart',
data: companyData
});
show-[relation].orgchart
Fires when a parent, child branch, or sibling branch becomes visible, as show-parent.orgchart, show-children.orgchart, or show-siblings.orgchart.
hide-[relation].orgchart
Fires when a parent, child branch, or sibling branch is hidden, as hide-parent.orgchart, hide-children.orgchart, or hide-siblings.orgchart.
export-error.orgchart
Fires on the chart when PNG/PDF rendering fails. The error is available as event.detail.error.
Advanced Examples
Add Employees From An Admin Form
<form id="add-report-form">
<label>
Manager ID
<select id="manager-id">
<option value="product-team">Product Team</option>
<option value="engineering-team">Engineering Team</option>
</select>
</label>
<label>
Employee name
<input id="employee-name" type="text" required>
</label>
<label>
Job title
<input id="employee-title" type="text" required>
</label>
<button type="submit">Add employee</button>
</form>
document.getElementById('add-report-form').addEventListener('submit', function(event) {
event.preventDefault();
var managerId = document.getElementById('manager-id').value;
var employeeName = document.getElementById('employee-name').value;
var employeeTitle = document.getElementById('employee-title').value;
var managerNode = document.getElementById(managerId);
if (!managerNode) {
return;
}
orgChart.addChildren(managerNode, [
{
id: 'employee-' + Date.now(),
name: employeeName,
title: employeeTitle
}
]);
var hierarchy = orgChart.getHierarchy(true);
console.log(hierarchy);
});
Build A Navigable Large Organization Chart
Use the companyData object from the basic example in a chart that starts with four visible levels and supports pan, zoom, and minimap navigation.
<div id="enterprise-chart"></div>
var largeOrgChart = new OrgChart({
chartContainer: '#enterprise-chart',
data: companyData,
nodeContent: 'title',
visibleLevel: 4,
direction: 'l2r',
pan: true,
zoom: true,
minimap: true
});
Load Organization Data From An API
Fetch the nested or flat JSON data from your application's /api/company/hierarchy endpoint, then initialize the chart with the response.
<div id="remote-org-chart"></div>
fetch('/api/company/hierarchy')
.then(function(response) {
if (!response.ok) {
throw new Error('Unable to load organization data.');
}
return response.json();
})
.then(function(data) {
window.remoteOrgChart = new OrgChart({
chartContainer: '#remote-org-chart',
data: data,
pan: true,
zoom: true
});
})
.catch(function(error) {
console.error(error);
});
Migrating jQuery OrgChart 5.x To OrgChart 8
1. Replace The jQuery Build
OrgChart 5.x:
<link rel="stylesheet" href="jquery.orgchart.css"> <script src="jquery.min.js"></script> <script src="jquery.orgchart.js"></script>
OrgChart 6.0.0+:
<link rel="stylesheet" href="orgchart.css"> <script src="orgchart.js"></script>
2. Replace The jQuery Plugin Call
OrgChart 5.x:
var oc = $('#chart-container').orgchart({
data: datasource,
nodeContent: 'title'
});
OrgChart 6.0.0+:
var oc = new OrgChart({
chartContainer: '#chart-container',
data: datasource,
nodeContent: 'title'
});
3. Pass Native DOM Elements To Methods
Node-related methods now take native HTMLElement objects.
OrgChart 5.x:
var $node = $('#manager');
oc.addChildren($node, newEmployees);
OrgChart 6.0.0+:
var node = document.getElementById('manager');
oc.addChildren(node, newEmployees);
4. Replace jQuery Events With Native Events
Use addEventListener() for OrgChart 6+ events and read event data from event.detail.
oc.chart.addEventListener('nodedrop.orgchart', function(event) {
var draggedNode = event.detail.draggedNode;
var dropZone = event.detail.dropZone;
});
5. Replace jQuery DOM Helpers
Standard DOM APIs replace jQuery helpers in custom OrgChart code.
// jQuery
$('.orgchart').addClass('noncollapsable');
// Vanilla JavaScript
oc.chart.classList.add('noncollapsable');
Alternatives & Related Resources:
- Fancytree: jQuery and jQuery UI Dynamic Tree View Plugin
- jsTree: Powerful Dynamic Tree Plugin With jQuery
- 10 Best Organization Chart JavaScript/CSS Libraries
- 10 Best JavaScript Tree View Libraries & Plugins
Changelog:
v8.0.0 (2026-11-03)
- Added flat
parent_iddatasources and thegetFlatDatasource()API. - Added expand/collapse interactions for family-tree branches.
v7.0.0 (2026-10-15)
- Fixed option compatibility issues.
- Removed three-bit relationship encoding,
attachRel, and therelationshipdata field. - Created branch expand/collapse controls on demand, reducing initial DOM elements in large charts.
- Moved asynchronous loading controls to application-level demo code.
v6.0.0 (2026-08-06)
- Rewritten with native JavaScript and removed the jQuery dependency.
- Switched to the
OrgChartconstructor, native DOM elements, and nativeCustomEventevents.
v5.0.0 (2024-12-15)
- Added Family Tree support.
v4.0.0 (2023-12-16)
- Removed the
ajaxURLoption. Applications now manage AJAX data loading directly. - Removed the
load-[relation].orgchartevents. - Added
addAncestors()andaddDescendants()methods.
v3.8.0 (2023-06-22)
- Added compact layouts through the
compactdata property and option.
v3.7.0 (2023-05-10)
- Added support for replacing the built-in icons with Font Awesome or other icon sets.
v3.5.0 (2023-02-23)
- Added per-branch vertical layouts through datasource properties.
v3.4.0 (2023-02-22)
- Added drag and drop support to hybrid horizontal and vertical charts.
v3.0.0 (2021-02-15)
- Rebuilt the chart structure with nested
<ul>elements instead of nested tables.
v2.2.0 (2021-01-07)
- Added a custom export button name.
- Added optional node data to
getHierarchy(). - Added events for AJAX insertion and branch visibility changes.
v2.1.10 (2020-01-21)
- Added built-in OCI icons and removed the Font Awesome dependency.
v2.0.16 (2018-01-12)
- Added touch support for node drag and drop.
This awesome jQuery plugin is developed by dabeng. For more Advanced Usages, please check the demo page or visit the official website.











