Here's a simple implementation of an expandable/collapsible treeview menu using plain HTML and JavaScript.
Step 1
Define your tree structure with HTML
Initially, you want to create a tree structure using nested unordered lists (<ul> and <li> tags). Let's use the following basic structure:
<ul id="myTree">
<li>
Parent 1
<ul>
<li>Child 1</li>
<li>Child 2</li>
</ul>
</li>
<li>
Parent 2
<ul>
<li>Child 3</li>
<li>Child 4</li>
</ul>
</li>
</ul>
Step 2
Style your menu with CSS
To make the tree menu look the way you want, you will want to add some CSS styles. Here is a simple example, which you can add to a <style> tag in the head of your HTML:
<style>
#myTree ul {display: none;}
#myTree li {cursor: pointer;}
</style>
Ask your specific question in Mate AI
In Mate you can connect your project, ask questions about your repository, and use AI Agent to solve programming tasks
This will hide all <ul> tags within the tree, effectively collapsing the tree. The cursor style is set to "pointer" to indicate that the list items are clickable.
Step 3
Add expand/collapse functionality with JavaScript
Now we need some JavaScript to expand and collapse each node when clicked. One way to do this is by adding a click event listener to each <li> tag in the tree:
<script>
document.querySelectorAll('#myTree li').forEach(function(el) {
el.addEventListener('click', function(event) {
let firstChild = this.firstElementChild;
if(firstChild && firstChild.tagName === 'UL') {
let display = firstChild.style.display;
firstChild.style.display = display === 'block' ? 'none' : 'block';
}
event.stopPropagation();
});
});
</script>
- We are selecting all <li> elements under the element with id "myTree" and adding a click event listener to each.
- In the event handler, we first get the li tag's first child element.
- Then, we check if the first child is a nested <ul>. If it is, we toggle its display style between 'none' and 'block'.
- The line event.stopPropagation(); is used to prevent events from bubbling up to parent elements. This ensures that when you click on an item, only the children of that item are expanded/collapsed.
This will make the nested lists collapsible. Clicking on a parent item will show its children in the list, and clicking on it again will hide the children.
That's it! You have a simple, expandable treeview menu with JavaScript and HTML. Of course, you can make it much fancier with additional CSS and JavaScript if you'd like.
AI agent for developers
Boost your productivity with Mate:
easily connect your project, generate code, and debug smarter - all powered by AI.
Do you want to solve problems like this faster? Download now for free.