Monday, November 9, 2026
HomejQueryOrgChart: Interactive Group Chart in Vanilla JavaScript

OrgChart: Interactive Group Chart in Vanilla JavaScript


OrgChart is a vanilla JavaScript library for constructing interactive group charts and household bushes from nested JSON knowledge or HTML lists. It additionally accepts flat parent_id information, with drag-and-drop modifying and expandable branches.

Options:

  • Renders nested JSON hierarchies, flat parent_id information, or nested <ul> markup.
  • Expands and collapses branches with CSS transitions.
  • Locations charts in top-to-bottom, bottom-to-top, left-to-right, or right-to-left layouts.
  • Helps pan, mouse-wheel zoom, and minimap navigation.
  • Reorders hierarchy nodes by means of drag and drop.
  • Provides, removes, and reorganizes nodes at runtime.
  • Retrieves edited charts as nested hierarchies or flat information by means of getHierarchy() and getFlatDatasource().
  • Exports charts to PNG or PDF.
  • Helps customized node markup and customized icon units.
  • Makes use of compact and hybrid layouts for dense hierarchies.
  • Builds household bushes from grouped hierarchy knowledge, with expandable and collapsible household branches.
  • Helps contact interplay on cellular gadgets.

Use Circumstances:

  • Map reporting traces inside an HR dashboard and let directors reorganize groups by means of drag and drop.
  • Construct an worker listing with customized node playing cards, collapsed departments, and several other hierarchy ranges.
  • Show a family tree or pedigree tree with spouses, youngsters, and customized household attributes.
  • Hint reporting relationships throughout a big group with a number of administration ranges.

Set up:


# npm
npm set up orgchart

# Legacy Bower set up
bower set up orgchart

Methods to use OrgChart:

Fundamental utilization:

Load the core stylesheet and JavaScript recordsdata in your doc.


<hyperlink rel="stylesheet" href="dist/css/orgchart.css">
<script src="dist/js/orgchart.js"></script>

<div id="company-org-chart"></div>

Cross the worker hierarchy to new OrgChart(). The chartContainer selector matches the container above, and nodeContent: 'title' shows job titles beneath worker names.


var companyData = {
  id: 'chief-executive',
  identify: 'Maya Chen',
  title: 'Chief Government Officer',
  youngsters: [
    {
      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',
      identify: 'Sam Rivera',
      title: 'VP of Engineering',
      youngsters: [
        {
          id: 'web-platform',
          name: 'Taylor Kim',
          title: 'Web Platform Lead'
        }
      ]
    }
  ]
};

var orgChart = new OrgChart({
  chartContainer: '#company-org-chart',
  knowledge: companyData,
  nodeContent: 'title',
  visibleLevel: 3
});

Flat Knowledge Supply With parent_id

Cross database-style information immediately as a flat array. Every parent_id references one other row’s id; one row will need to have a null or omitted mother or father. 


<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',
  knowledge: teamRows,
  pan: true,
  zoom: true
});

OrgChart Knowledge Construction

Node knowledge defines IDs, show fields, CSS courses, and enlargement state. OrgChart derives mother or father and sibling relationships from the loaded hierarchy.

  • id: Identifies every node for modifying and hierarchy export. Use distinctive values.
  • youngsters: Comprises nested descendant knowledge.
  • parent_id: Identifies the mother or father in a flat knowledge supply; use null or omit it for the foundation.
  • collapsed: Hides a node’s descendants initially when set to true.
  • className: Provides customized CSS courses to the rendered node.
  • hybrid: Arranges descendants vertically when the worth is truthy.
  • compact: Makes use of a compact format for the node’s descendants when truthy.
  • outsider: Marks an outdoor member in family-tree knowledge.

var departmentData = {
  id: 'operations',
  identify: 'Operations',
  title: 'Division',
  className: 'department-node',
  collapsed: false,
  youngsters: [
    {
      id: 'facilities',
      name: 'Facilities',
      title: 'Team'
    },
    {
      id: 'procurement',
      name: 'Procurement',
      title: 'Team'
    }
  ]
};

OrgChart Choices

Knowledge And Navigation Choices

  • knowledge (Object, Array, or HTMLUListElement, required): Accepts a nested JSON tree, flat parent_id rows, grouped household knowledge, or an HTML checklist.
  • pan (Boolean, default false): Lets customers transfer the chart by dragging the chart space.
  • zoom (Boolean, default false): Prompts mouse-wheel zoom.
  • minimap (Boolean, default false): Provides an summary navigator for big charts.
  • zoominLimit (Quantity, default 7): Units the utmost zoom-in scale.
  • zoomoutLimit (Quantity, default 0.5): Units the minimal zoom-out scale.
  • visibleLevel (Nonnegative Integer or Boolean, default 999): Units preliminary enlargement depth. false exhibits the primary stage; 0 hides all preliminary nodes.

Structure Choices

  • route (String, default "t2b"): Units chart route. Supported values are t2b, b2t, l2r, and r2l.
  • verticalLevel (Integer, minimal 2): Begins vertical youngster alignment from a specified hierarchy stage.
  • toggleSiblingsResp (Boolean, default false): Provides separate controls for displaying or hiding left and proper siblings.
  • chartClass (String, default ""): Provides a customized class to the chart. This helps distinguish a number of OrgChart cases on one web page.
  • compact (Boolean or Perform): Set true to compact each department, or go a perform that selects nodes for compact format. Node-level compact values are additionally supported.

Node Content material Choices

  • nodeTitle (String, default "identify"): Selects the info property used for the principle node title.
  • nodeContent (String): Selects the info property used for the secondary content material space.
  • nodeId (String, default "id"): Selects the info property used as every node’s distinctive identifier.
  • nodeTemplate (Perform): Returns customized HTML for every node. Sanitize dynamic markup earlier than returning it.
  • createNode (Perform): Receives the rendered node ingredient and its knowledge after node creation.

<div id="employee-chart"></div>

var employeeChart = new OrgChart({
  chartContainer: '#employee-chart',
  knowledge: companyData,
  nodeContent: 'title',
  createNode: perform(node, knowledge) {
    if (knowledge.title) {
      node.setAttribute('data-job-title', knowledge.title);
    }
  }
});

Drag And Drop Choices

  • draggable (Boolean, default false): Prompts node drag and drop.
  • dropCriteria (Perform): Receives draggedNode, dragZone, and dropZone. Return a Boolean worth to simply accept or reject the connection change.

<div id="editable-org-chart"></div>

var editableChart = new OrgChart({
  chartContainer: '#editable-org-chart',
  knowledge: companyData,
  draggable: true,
  dropCriteria: perform(draggedNode, dragZone, dropZone) {
    return draggedNode.id !== 'engineering-team';
  }
});

Export Choices

PNG and PDF export use html2canvas, and PDF additionally requires jsPDF. When loading OrgChart immediately within the browser, load the browser builds of these libraries earlier than exporting.

  • exportButton (Boolean, default false): Provides the built-in export button.
  • exportButtonName (String, default "Export"): Units the export button label.
  • exportFilename (String, default "OrgChart"): Units the downloaded file identify.
  • exportFileextension (String, default "png"): Selects png or pdf.
  • exportScale (Quantity, default 2): Units the render scale used throughout chart export.

Lifecycle And Icon Choices

  • initCompleted (Perform): Runs after the chart finishes its preliminary render. It receives the rendered chart ingredient.
  • icons (Object): Replaces the built-in icon class map. You need to use one other icon library comparable to Font Superior.

Load the icon pack’s CSS earlier than utilizing its class names.


<div id="icon-chart"></div>

var iconChart = new OrgChart({
  chartContainer: '#icon-chart',
  knowledge: 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'
  }
});

Customise Chart CSS

OrgChart exposes CSS variables for node dimensions, connector colours, hover states, and department transitions.


.orgchart {
  --oc-node-width: 180px;
  --oc-line-color: #777;
  --oc-duration: 250ms;
}

OrgChart API Strategies

The occasion properties chartContainer and chart reference its native container and rendered chart parts.

Initialization And Runtime Choices

  • orgChart.init(choices): Rebuilds the chart with updated choices or knowledge. It returns the OrgChart occasion.
  • orgChart.setOptions(choices): Updates a partial set of settings. Navigation and export settings replace in place; knowledge, format, and node-rendering modifications rebuild the chart. Returns the OrgChart occasion.
  • orgChart.setOptions(identify, worth): Updates a single possibility by identify, together with navigation and export settings. Returns the OrgChart occasion.
  • orgChart.destroy(): Removes generated chart sources, releases listeners, and restores managed container kinds. Returns the occasion.

orgChart.setOptions('minimap', true);

orgChart.setOptions({
  pan: true,
  zoom: true
});

orgChart.init({
  knowledge: departmentData
});

Minimap Strategies

Use setOptions('minimap', true) or setOptions('minimap', false) for UI toggles to maintain the choice worth synchronized with the navigator.

  • orgChart.attachMinimap(): Creates the minimap for the present chart.
  • orgChart.detachMinimap(): Removes the minimap.
  • orgChart.updateMinimap(forceRefresh): Recalculates minimap state. Cross true to redraw its node preview.

Hierarchy Modifying Strategies

For on-demand loading, deal with the request in your software and insert the returned nodes by means of addAncestors(), addDescendants(), or addChildren().

  • orgChart.addAncestors(knowledge, parentId): Provides ancestor knowledge above the present hierarchy and attaches the present root to parentId.
  • orgChart.addDescendants(knowledge, mother or father): Provides descendant knowledge beneath a local mother or father node ingredient.
  • orgChart.addParent(currentRoot, knowledge): Wraps the present root with a brand new mother or father node.
  • orgChart.addSiblings(node, knowledge): Provides sibling nodes beside a local node ingredient.
  • orgChart.addChildren(node, knowledge): Provides youngster nodes beneath a local node ingredient.
  • orgChart.removeNodes(node): Removes a node and its descendants.

var engineeringNode = doc.getElementById('engineering-team');

orgChart.addChildren(engineeringNode, [
  {
    id: 'quality-engineering',
    name: 'Quality Engineering',
    title: 'Team'
  }
]);

Hierarchy Question Strategies

  • orgChart.getHierarchy(includeNodeData): Returns the hierarchy. Cross true to incorporate node knowledge together with IDs and youngsters.
  • orgChart.getFlatDatasource(): Returns the present hierarchy as flat information, recalculating parent_id for every loaded node, together with hidden descendants.
  • orgChart.getNodeState(node, relation): Returns { exist, seen } for mother or father, youngsters, or siblings.
  • orgChart.getParent(node): Returns the direct mother or father node or null.
  • orgChart.getChildren(node): Returns an array of direct youngster node parts.
  • orgChart.getSiblings(node): Returns an array of direct sibling node parts.
  • orgChart.getRelatedNodes(node, relation): Queries mother or father, youngsters, or siblings by means of one generalized technique.

var productNode = doc.getElementById('product-team');

var youngsters = orgChart.getChildren(productNode);
var mother or father = orgChart.getParent(productNode);
var state = orgChart.getNodeState(productNode, 'youngsters');

console.log(youngsters);
console.log(mother or father);
console.log(state);
console.log(orgChart.getFlatDatasource());

Department Visibility Strategies

  • orgChart.hideParent(node): Hides a node’s mother or father and the associated sibling department.
  • orgChart.showParent(node): Reveals the mother or father department.
  • orgChart.hideChildren(node): Hides direct youngster branches.
  • orgChart.showChildren(node): Reveals youngster branches.
  • orgChart.hideSiblings(node, route): Hides siblings. Set route to left or proper, or omit it for either side.
  • orgChart.showSiblings(node, route): Reveals siblings on one facet or either side.

Zoom Technique

  • orgChart.setChartScale(chart, multiplier, zoomAnchor): Adjustments chart scale throughout the configured zoom limits. zoomAnchor accepts viewport coordinates within the kind { x, y }.

orgChart.setChartScale(orgChart.chart, 1.2, {
  x: window.innerWidth / 2,
  y: window.innerHeight / 2
});

Export Strategies

  • orgChart.export(filename, extension): Downloads a PNG or PDF and returns a Promise resolving to its rendered canvas. Returns false when export can not start; rejects the Promise and dispatches export-error.orgchart on failure.
  • orgChart.exportPNG(canvas, filename): Downloads a ready canvas as PNG.
  • orgChart.exportPDF(canvas, filename, exportScale): Downloads a ready canvas as PDF.

var consequence = orgChart.export('engineering-structure', 'png');
if (consequence) {
  consequence.catch(perform(error) {
    console.error('Chart export failed:', error);
  });
}

OrgChart Occasions

nodedrop.orgchart

Fires earlier than a node strikes. Learn draggedNode, dragZone, and dropZone from occasion.element. Name occasion.preventDefault() to cancel the drop.


orgChart.chart.addEventListener('nodedrop.orgchart', perform(occasion) {
  var element = occasion.element;

  console.log('Dragged node:', element.draggedNode);
  console.log('Drop goal:', element.dropZone);
});

otherdropped.orgchart

Fires when an exterior draggable merchandise is dropped onto a chart node. occasion.element incorporates draggedItem and dropZone.

init.orgchart

Fires when the chart finishes rendering. To catch the primary render, register a listener on its container earlier than initialization.


<div id="event-org-chart"></div>

var eventContainer = doc.getElementById('event-org-chart');
eventContainer.addEventListener('init.orgchart', perform(occasion) {
  console.log('Chart initialized:', occasion.goal);
});

var eventChart = new OrgChart({
  chartContainer: '#event-org-chart',
  knowledge: companyData
});

show-[relation].orgchart

Fires when a mother or father, youngster department, or sibling department turns into seen, as show-parent.orgchart, show-children.orgchart, or show-siblings.orgchart.

hide-[relation].orgchart

Fires when a mother or father, youngster department, or sibling department 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 obtainable as occasion.element.error.

Superior Examples

Add Staff From An Admin Type


<kind id="add-report-form">
  <label>
    Supervisor ID
    <choose id="manager-id">
      <possibility worth="product-team">Product Workforce</possibility>
      <possibility worth="engineering-team">Engineering Workforce</possibility>
    </choose>
  </label>

  <label>
    Worker identify
    <enter id="employee-name" sort="textual content" required>
  </label>

  <label>
    Job title
    <enter id="employee-title" sort="textual content" required>
  </label>

  <button sort="submit">Add worker</button>
</kind>

doc.getElementById('add-report-form').addEventListener('submit', perform(occasion) {
  occasion.preventDefault();

  var managerId = doc.getElementById('manager-id').worth;
  var employeeName = doc.getElementById('employee-name').worth;
  var employeeTitle = doc.getElementById('employee-title').worth;

  var managerNode = doc.getElementById(managerId);

  if (!managerNode) {
    return;
  }

  orgChart.addChildren(managerNode, [
    {
      id: 'employee-' + Date.now(),
      name: employeeName,
      title: employeeTitle
    }
  ]);

  var hierarchy = orgChart.getHierarchy(true);

  console.log(hierarchy);
});

Construct A Navigable Massive Group Chart

Use the companyData object from the fundamental instance in a chart that begins with 4 seen ranges and helps pan, zoom, and minimap navigation.


<div id="enterprise-chart"></div>

var largeOrgChart = new OrgChart({
  chartContainer: '#enterprise-chart',
  knowledge: companyData,
  nodeContent: 'title',
  visibleLevel: 4,
  route: 'l2r',
  pan: true,
  zoom: true,
  minimap: true
});

Load Group Knowledge From An API

Fetch the nested or flat JSON knowledge out of your software’s /api/firm/hierarchy endpoint, then initialize the chart with the response.


<div id="remote-org-chart"></div>

fetch('/api/firm/hierarchy')
  .then(perform(response) {
    if (!response.okay) {
      throw new Error('Unable to load group knowledge.');
    }

    return response.json();
  })
  .then(perform(knowledge) {
    window.remoteOrgChart = new OrgChart({
      chartContainer: '#remote-org-chart',
      knowledge: knowledge,
      pan: true,
      zoom: true
    });
  })
  .catch(perform(error) {
    console.error(error);
  });

Migrating jQuery OrgChart 5.x To OrgChart 8

1. Change The jQuery Construct

OrgChart 5.x:


<hyperlink rel="stylesheet" href="jquery.orgchart.css">
<script src="jquery.min.js"></script>
<script src="jquery.orgchart.js"></script>

OrgChart 6.0.0+:


<hyperlink rel="stylesheet" href="orgchart.css">
<script src="orgchart.js"></script>

2. Change The jQuery Plugin Name

OrgChart 5.x:


var oc = $('#chart-container').orgchart({
  knowledge: datasource,
  nodeContent: 'title'
});

OrgChart 6.0.0+:


var oc = new OrgChart({
  chartContainer: '#chart-container',
  knowledge: datasource,
  nodeContent: 'title'
});

3. Cross Native DOM Parts To Strategies

Node-related strategies now take native HTMLElement objects.

OrgChart 5.x:


var $node = $('#supervisor');
oc.addChildren($node, newEmployees);

OrgChart 6.0.0+:


var node = doc.getElementById('supervisor');
oc.addChildren(node, newEmployees);

4. Change jQuery Occasions With Native Occasions

Use addEventListener() for OrgChart 6+ occasions and browse occasion knowledge from occasion.element.


oc.chart.addEventListener('nodedrop.orgchart', perform(occasion) {
  var draggedNode = occasion.element.draggedNode;
  var dropZone = occasion.element.dropZone;
});

5. Change jQuery DOM Helpers

Customary DOM APIs substitute jQuery helpers in customized OrgChart code.


// jQuery
$('.orgchart').addClass('noncollapsable');

// Vanilla JavaScript
oc.chart.classList.add('noncollapsable');

Options & Associated Assets:

Changelog:

v8.0.0 (2026-11-03)

  • Added flat parent_id datasources and the getFlatDatasource() API.
  • Added increase/collapse interactions for family-tree branches.

v7.0.0 (2026-10-15)

  • Fastened possibility compatibility points.
  • Eliminated three-bit relationship encoding, attachRel, and the relationship knowledge discipline.
  • Created department increase/collapse controls on demand, decreasing preliminary DOM parts in massive charts.
  • Moved asynchronous loading controls to application-level demo code.

v6.0.0 (2026-08-06)

  • Rewritten with native JavaScript and eliminated the jQuery dependency.
  • Switched to the OrgChart constructor, native DOM parts, and native CustomEvent occasions.

v5.0.0 (2024-12-15)

  • Added Household Tree assist.

v4.0.0 (2023-12-16)

  • Eliminated the ajaxURL possibility. Functions now handle AJAX knowledge loading immediately.
  • Eliminated the load-[relation].orgchart occasions.
  • Added addAncestors() and addDescendants() strategies.

v3.8.0 (2023-06-22)

  • Added compact layouts by means of the compact knowledge property and possibility.

v3.7.0 (2023-05-10)

  • Added assist for changing the built-in icons with Font Superior or different icon units.

v3.5.0 (2023-02-23)

  • Added per-branch vertical layouts by means of datasource properties.

v3.4.0 (2023-02-22)

  • Added drag and drop assist to hybrid horizontal and vertical charts.

v3.0.0 (2021-02-15)

  • Rebuilt the chart construction with nested <ul> parts as a substitute of nested tables.

v2.2.0 (2021-01-07)

  • Added a customized export button identify.
  • Added elective node knowledge to getHierarchy().
  • Added occasions for AJAX insertion and department visibility modifications.

v2.1.10 (2020-01-21)

  • Added built-in OCI icons and eliminated the Font Superior dependency.

v2.0.16 (2018-01-12)

  • Added contact assist for node drag and drop.

This superior jQuery plugin is developed by dabeng. For extra Superior Usages, please test the demo web page or go to the official web site.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments