A simple nested tree menu with vanilla js and css

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

Making it interactive using css and js

Step 1: Remove the default ul styling

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

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

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

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.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store