Create Dynamic Tree View Using JavaScript

Create Dynamic Tree View Using JavaScript
Code Snippet:Dynamic tree view
Author: Ross Angus
Published: May 1, 2024
Last Updated: May 1, 2024
Downloads: 54
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code helps you to create a Dynamic tree view. It allows users to manipulate tree nodes easily. Moreover, by clicking nodes, users can select, edit, delete, and add new nodes. The tree layout adjusts dynamically. It helps organize hierarchical data visually.

You can use this  JavaScript code to implement interactive tree structures in web applications. It helps organize hierarchical data like file directories, organizational charts, or menu structures. With its customization options and keyboard support, it enhances user experience and accessibility.

How to Create Create Dynamic Tree View Using JavaScript

1. Start by defining the HTML structure for the tree view. Use <ul> and <li> tags to represent parent and child nodes, and <button> tags for node buttons.

<p role="toolbar" aria-label="Node tools" aria-hidden="true" class="toolbar">
  <button type="button" data-js="promoteSibling">&laquo; Move left</button>
  <button type="button" data-js="demoteSibling">Move right &raquo;</button>
  <button type="button" data-js="addChild">+ Add new</button>
  <button type="button" data-js="deleteNode">
    &times; Delete
    <ins role="alert" aria-hidden="true" class="confirm" aria-label="Please confirm deletion">Are you sure? (press again to continue)</ins>
    <ins role="alert" aria-hidden="true" class="root" aria-label="You can't delete root">You can't delete the root node</ins>
  </button>
  <button type="button" data-js="editName">✎ Edit name</button>
</p>

<details>
  <summary>Customise your tree view</summary>
  <div class="grid">
    <p><label for="line-color">Line colour</label> <input type="color" id="line-color" name="line-color" value="#666"></p>
    <p><label for="line-width">Line width</label> <input type="range" id="line-width" name="line-width"  value="1" min="1" max="10"></p>
    <p><label for="gutter">Gutters</label> <input type="range" id="gutter" name="gutter" value="5" min="1" max="10"></p>
  </div>
</details>
  
<ul class="tree">
  <li>
    <button type="button" aria-pressed="false" data-js="node">Home</button>
    <ul>
      <li><button type="button" aria-pressed="false" data-js="node">One</button></li>
      <li><button type="button" aria-pressed="false" data-js="node">Two</button></li>
      <li><button type="button" aria-pressed="false" data-js="node">Three</button></li>
    </ul>
  </li>
</ul>

2. Apply CSS styles to create the visual layout of the tree view. Use CSS to customize node appearance, line colors, and spacing.

:root {
  --line-color: #666;
  --line-width: .1em;
  --gutter: .5em;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}

*, *:before, *:after {
  box-sizing: border-box;
}

.tree {
  margin: 0 0 calc(var(--gutter) * 2);
  text-align: center;
  /* _________ */
  /* | */
  /* The root node doesn't connect upwards */
}
.tree, .tree ul, .tree li {
  list-style: none;
  margin: 0;
  padding: 0;
  position: relative;
}
.tree, .tree ul {
  display: table;
}
.tree ul {
  width: 100%;
}
.tree li {
  display: table-cell;
  padding: var(--gutter) 0;
  vertical-align: top;
}
.tree li:before {
  content: "";
  left: 0;
  outline: solid calc(var(--line-width) /2) var(--line-color);
  position: absolute;
  right: 0;
  top: 0;
}
.tree li:first-child:before {
  left: 50%;
}
.tree li:last-child:before {
  right: 50%;
}
.tree button {
  border-radius: 0.2em;
  margin: 0 calc(var(--gutter) / 2) var(--gutter);
  min-height: 2.1em;
  position: relative;
  z-index: 1;
}
.tree [contenteditable] {
  cursor: text;
}
.tree .selected {
  border-color: #900;
  border-style: dashed;
  -webkit-box-shadow: 0 0 var(--gutter) var(--line-width) rgba(153, 0, 0, 0.3);
  -moz-box-shadow: 0 0 var(--gutter) var(--line-width) rgba(153, 0, 0, 0.3);
  box-shadow: 0 0 var(--gutter) var(--line-width) rgba(153, 0, 0, 0.3);
}
.tree ul:before, .tree button:before {
  outline: solid calc(var(--line-width) / 2) var(--line-color);
  content: "";
  height: var(--gutter);
  left: 50%;
  position: absolute;
  top: calc(calc(-1 * var(--gutter)) - calc(var(--line-width) / 2));
}
.tree > li {
  margin-top: 0;
}
.tree > li:before, .tree > li:after, .tree > li > button:before {
  outline: none;
}

button {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: #fff;
  border: solid var(--line-width) var(--line-color);
  cursor: pointer;
  font-size: 1em;
  line-height: 1.2em;
  padding: 0.4em 1em;
  position: relative;
}
button:focus, button:hover {
  outline: 0.1em dotted var(--line-color);
  outline-offset: -0.5em;
}

input[type=range] {
  display: block;
  width: 100%;
}

input[type=color] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  border: none;
  cursor: pointer;
  display: block;
  height: 2em;
  padding: 0;
  vertical-align: middle;
  width: 100%;
}

.toolbar {
  background: #ccc;
  font-size: 0.9em;
  left: 0;
  margin: 0;
  padding: var(--gutter);
  position: fixed;
  right: 0;
  text-align: center;
  top: 0;
  transform: translate(0, -100%);
  transition: all 0.2s ease;
  z-index: 2;
}

.toolbar.show {
  transform: translate(0, 0);
}

ins {
  background: #fff;
  border: solid calc(var(--line-width) /2) var(--line-color);
  display: inline-block;
  font-size: 0.8em;
  left: -1em;
  margin: 1em 0 0;
  padding: 0.2em 0.5em;
  position: absolute;
  right: -1em;
  text-decoration: none;
  top: 100%;
}
ins:before, ins:after {
  border: solid 1em transparent;
  border-top: none;
  content: "";
  left: 50%;
  position: absolute;
  transform: translate(-50%, 0);
}
ins:before {
  border-bottom-color: var(--line-color);
  bottom: 100%;
}
ins:after {
  bottom: calc(100% - var(--line-width));
  border-bottom-color: #fff;
}

ins {
  opacity: 0;
  transition: all 0.2s ease;
  transform: scale(0, 0);
}

.js-confirm .confirm, .js-root .root {
  opacity: 1;
  transform: scale(1, 1);
}

.grid {
  display: flex;
  width: 100%;
}
.grid > * {
  flex: 1;
  margin-left: 0.5em;
  margin-right: 0.5em;
}

3. Implement JavaScript functions to handle user interactions such as adding, deleting, and editing nodes.

var root         = document.documentElement,
    toolBar      = document.querySelector('[role="toolbar"]'),
    colorInput   = document.querySelector('#line-color'),
    lineInput    = document.querySelector('#line-width'),
    gutterInput  = document.querySelector('#gutter'),
    alertRoot    = document.querySelector('[data-js="deleteNode"] .root'),
    alertConfirm = document.querySelector('[data-js="deleteNode"] .confirm'),
    // Used for naming new nodes
    nodeNames    = ["Dolor", "Amet", "Consectetur", "Adipiscing", "Elit", "Nunc", "Sagittis", "Pretium", "Convallis", "Curabitur", "Turpis", "Velit", "Vitae", "Rutrum",  "Sapien", "Orci", "Tempor", "Elementum",  "Risus", "Etiam", "Ante", "Hendrerit", "Malesuada", "Donec", "Porttitor", "Eget", "Libero", "Pharetra", "Aliquam", "Mattis", "Massa", "Porta", "Morbi", "Augue", "Lectus", "Tellus", "Facilisis", "Tincidunt", "Suspendisse", "Eros", "Magna", "Consequat", "Sollicitudin", "Vestibulum", "Egestas", "Quis", "Lacus", "Molestie",  "Scelerisque", "Nullam", "Tortor", "Aenean", "Pulvinar", "Odio", "Placerat", "Fringilla", "Neque"];

// All the button and body clicks are intercepted here.
document.addEventListener('click', function (e) {
  var clickType = e.target.getAttribute('data-js');
  // User has selected a node
  if (clickType === 'node') {
    selectNode(e);
  } else if (clickType !== '' && clickType !== null) {
    // Buttons within the toolbar, at the top of the page
    if      (clickType === 'promoteSibling') promoteSibling();
    else if (clickType === 'demoteSibling')  demoteSibling();
    else if (clickType === 'editName')       editName();
    else if (clickType === 'deleteNode')     deleteNode(e);
    else if (clickType === 'addChild')       addChild();
  } else {
    // User has clicked outside of a node
    deselectNodes();
    hideToolbar();
  }
});

// Customise views events
colorInput.addEventListener('change', lineColor);
lineInput.addEventListener('change', lineWidth);
gutterInput.addEventListener('change', gutterWidth);

function lineColor(e) {
  root.style.setProperty('--line-color', e.target.value);
}
function lineWidth(e) {
  root.style.setProperty('--line-width', (e.target.value / 10) + 'em');
}
function gutterWidth(e) {
  root.style.setProperty('--gutter', (e.target.value / 10) + 'em');
}

// Allows the user to reorder the tree with the keyboard
root.addEventListener('keydown', function (e) {
  var keyPress;
  // New method vs. old method
  if (e.key) keyPress = e.key;
  else       keyPress = e.which;
  // If the user is editing a node name, they might need to use the arrow keys As God Intended
  if (e.target.getAttribute('contenteditable')) {
    if (keyPress === ' ' || keyPress === '32') {
      insertTextAtCursor(' ');
    }
  } else {
    if (keyPress === 'ArrowRight' || keyPress === '37') {
      demoteSibling();
    } else if (keyPress === 'ArrowLeft' || keyPress === '39') {
      promoteSibling();
    }
  }
  // This is useful whether the user is editing the button or not
  if (keyPress === 'ArrowDown' || keyPress === '40') {
    addChild();
  }
});

// Deselects all other nodes, selects the current node and hoyks in the toolber
function selectNode(e) {
  var clicker = e.target;
  // Hang on - do we need to do anything?
  if (clicker.getAttribute('aria-pressed') === 'false') {
    deselectNodes();
    clicker.setAttribute('aria-pressed', 'true');
    clicker.classList.add('selected');
    showToolbar();   
  }
}

// Bit of cleanup, after the user has finished editing the tree.
function deselectNodes() {
  // This needs to run from scratch as new nodes might have been added
  var selectedBtns = [...document.querySelectorAll('.tree [aria-pressed="true"]')],
      btnDelete = document.querySelector('[data-js="deleteNode"]'),
      editBtns = [...document.querySelectorAll('.tree [contenteditable]')];
  // I mean, in theory, there should only be one selected button, but, you know, bugs...
  for (var i = 0; i < selectedBtns.length; i++) {
    selectedBtns[i].setAttribute('aria-pressed', 'false');
    selectedBtns[i].classList.remove('selected');
  }
  // Bit of cleanup, in case the user noped out of deleting a node
  if (btnDelete.classList.contains('js-confirm')) {
    btnDelete.classList.remove('js-confirm');
    alertConfirm.setAttribute('aria-hidden','true');
  }
  if (btnDelete.classList.contains('js-root')) {
    btnDelete.classList.remove('js-root');
    alertRoot.setAttribute('aria-hidden','true');
  }
  // Checks for new nodes which are editable, then turns them off.
  for (var i = 0; i < editBtns.length; i++) {
    editBtns[i].removeAttribute('contenteditable');
  }
}

function showToolbar() {
  toolBar.removeAttribute('aria-hidden');
  toolBar.classList.add('show');
}

function hideToolbar() {
  toolBar.setAttribute('aria-hidden','true');
  toolBar.classList.remove('show');
}

// Moves the sibling to the left
function promoteSibling() {
  if (document.querySelector('.tree .selected')) {
    var favouriteChild = document.querySelector('.tree .selected').parentNode,
        elderChild = favouriteChild.previousElementSibling;
    // Does this selected element have anywhere to go?
    if (elderChild) {
      favouriteChild.parentNode.insertBefore(favouriteChild,elderChild);
    }    
  }
}

// Moves the sibling to the right
function demoteSibling() {
  if (document.querySelector('.tree .selected')) {
    var chosenChild = document.querySelector('.tree .selected').parentNode,
        youngerChild = chosenChild.nextElementSibling;
    // Does this selected element have anywhere to go?
    if (youngerChild) {
      chosenChild.parentNode.insertBefore(youngerChild,chosenChild);
    }    
  }
}

// Allows the user to rename existing nodes
function editName() {
  var chosenChild = document.querySelector('.tree .selected');
  chosenChild.setAttribute('contenteditable', 'true');
  chosenChild.focus();
}

// Removes the node and it's children
function deleteNode(e) {
  var chosenChild  = document.querySelector('.tree .selected'),
      delButton    = e.target,
      isRoot       = chosenChild.parentNode.parentNode.classList.contains('tree');
  
  // Is the user trying to delete the root node?
  if (isRoot) {
    delButton.classList.add('js-root');
    alertRoot.removeAttribute('aria-hidden');
  }
  // Has the user clicked the delete button once already?
  else if (delButton.classList.contains('js-confirm')) {
    // Is there more than one sibling?
    if (chosenChild.parentNode.parentNode.childElementCount > 1) {
      chosenChild.parentNode.remove();
    } else { // Remove the whole list
      chosenChild.parentNode.parentNode.remove();
    }
    deselectNodes();
    hideToolbar();
  } else {
    delButton.classList.add('js-confirm');
    alertConfirm.removeAttribute('aria-hidden');
  }
}

// Adds a new node under the current node
function addChild() {
  if (document.querySelector('.tree .selected')) {
    var chosenNode = document.querySelector('.tree .selected').parentNode,
        listItem = document.createElement('li');
    listItem.innerHTML = '<button type="button" aria-pressed="false" data-js="node" contenteditable="true">' +
      nodeNames[Math.round(Math.random() * (nodeNames.length - 1))] + '</button>';
    // The current node already has kids
    if (chosenNode.querySelector('ul')) {
      var chosenKids = chosenNode.querySelector('ul');
      chosenKids.appendChild(listItem);
      chosenKids.lastChild.querySelector('button').focus();
    } else { // The current node has no kids
      var newDad = document.createElement('ul');
      newDad.appendChild(listItem);
      chosenNode.appendChild(newDad);
      chosenNode.lastChild.querySelector('button').focus();
    }    
  }
}

// Because each node is a button tag, the space bar event is captured, when the user is editing.
// This is used as a work-around.
function insertTextAtCursor(text) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode( document.createTextNode(text) );
        }
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().text = text;
    }
}

Finally, you’ve now created a dynamic tree view using HTML, CSS, and JavaScript. This interactive component allows users to navigate hierarchical data easily and provides a visually appealing way to represent complex structures. Experiment with different customization options to tailor it to your specific needs.

Leave a Comment