Created
August 1, 2020 18:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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