Skip to content

Instantly share code, notes, and snippets.

@irealworlds
Created August 1, 2020 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irealworlds/67e0411f70f533c750753f1c909ef5d2 to your computer and use it in GitHub Desktop.
Save irealworlds/67e0411f70f533c750753f1c909ef5d2 to your computer and use it in GitHub Desktop.
A function that helps quickly create trees in javascript, with a minimum amount of HTML required.
const CreateTree = element => {
const clickEvent = new Event('click');
const openedClass = 'fa-minus-circle';
const closedClass = 'fa-plus-circle';
//initialize each of the top levels
element.classList.add('tree');
for (let child of element.querySelectorAll('li')) {
if (child.getElementsByTagName('ul').length) {
const newNode = document.createElement('i');
newNode.classList.add('indicator');
newNode.classList.add('fa');
newNode.classList.add(closedClass);
child.prepend(newNode);
child.classList.add('branch');
child.addEventListener('click', event => {
if (event.target === child) {
const icon = child.querySelector('i');
if (icon.classList.contains(openedClass)) {
icon.classList.remove(openedClass);
icon.classList.add(closedClass);
} else {
icon.classList.remove(closedClass);
icon.classList.add(openedClass);
}
for (let branch of child.children) {
for (let twig of branch.children) {
if (twig.style.display === 'none') {
twig.style.display = 'block';
} else {
twig.style.display = 'none';
}
}
}
}
});
for (let branch of child.children) {
for (let twig of branch.children) {
if (twig.style.display === 'none') {
twig.style.display = 'block';
} else {
twig.style.display = 'none';
}
}
}
}
}
for (let icon of element.querySelectorAll('i.fa')) {
icon.addEventListener('click', event => {
event.preventDefault();
icon.parentNode.dispatchEvent(clickEvent);
});
}
//fire event to open branch if the li contains an anchor instead of text
// for (let link of element.querySelectorAll('.branch>a')) {
// link.addEventListener('click', event => {
// event.preventDefault();
// link.parentNode.dispatchEvent(clickEvent);
// });
// }
//fire event to open branch if the li contains a button instead of text
for (let button of element.querySelectorAll('.branch>button')) {
button.addEventListener('click', event => {
event.preventDefault();
button.parentNode.dispatchEvent(clickEvent);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment