A simple nested tree menu with vanilla js and css

Surya Sankar
3 min readMar 7, 2021

While building a dashboard layout, I recently had a requirement for a nested tree menu. It would preferably have to support any arbitrary level of nesting. There were some packages available already like JSTree — but they were built to support a lot of extra functionalities like changing the menu theme, adding branches dynamically etc which made them bigger than I needed them to be. I didn’t need any of those features and hence decided to build it myself. This short post is intended to document the same

Designing the html structure

The default choice for any menu type structure is to go with unordered lists. We can do the same here. We just need to make sure that the structure supports deep nesting and sub-headings for sub-menus. At the bare minimum it would look like this

Making it interactive using css and js

Here we implement the styling and scripts that would make this a proper nested menu

Step 1: Remove the default ul styling

Step 2: Add a click handler which expands and collapses the submenu

We do this by targeting all the elements with the submenu heading’s class name and then setting it’s sibling element’s (which would be the submenu ul) display to none (to hide it by default). Then we add a click handler on the submenu heading div which toggles the sibling submenu ul’s display property between none and block

Step 3: Add + and — markers next to the headings to denote its state

The menu headings should show a plus next to them when they are in a collapsed state indicating that they can be expanded and a minus next to them when they are expanded.

To do this we first add two classes — collapsed and expanded on the submenu heading which add the characters + and -

And then we add the logic to add and remove the classes to the event handler

Step 4: Add a submenu boundary when it is expanded

A final touch would be to add a dotted boundary on the left when a submenu is expanded — which lets the user see clearly which items are in the same level of nesting. To do this we add the following css

Since we have already added the styling and logic for hiding and showing this class, this boundary also will be hidden and shown along with it.

And that finishes our work. Combining it all together, here is a sample html with the styling and the script which achieves the nested menu functionality. Copy and paste this html and open it via a browser, it will have the functionality demonstrated by the cover image at the top of this post.

Now that it is working as expected, we will next see how we can convert this into a reusable library in the next post.

Originally published at https://techonometrics.com.

--

--

Surya Sankar

Entrepreneur, Full stack web developer, Product Manager. Dabbling with data science now. Interested in Economics, Politics and History.