I have bare basic knowledge in JavaScript, and I'm trying to create a menu where :
- Only the first level parents are visible.
- Then when you click on them, their children will be displayed.
- If you click on them again (or maybe click anywhere on the page) they will close
- Must work for 2 level children (for example children of children)
This is what I have so far, and I know this is far from being right. I found a bunch of jQuery solutions online, but I want it pure JavaScript & CSS.
Note: I also need to keep the number of classes & id's used to a minimum as I want to be able to use this with the WordPress menu structure. But if I need to manually add a "parent" class to each parent that has children, then that will be fine.
My JavaScript :
var menuParents = document.querySelectorAll("#my-menu .parent");
menuParents.forEach(menuParent => {
document.querySelector("#my-menu .parent").addEventListener("click", ToggleMenu);
function ToggleMenu() {
document.querySelector("#my-menu .parent ul").style.display = 'block';
}
});
My CSS :
#my-menu .parent ul {display: none;}
And, finally, my HTML :
<ul id="my-menu">
<li>Standard Item</li>
<li>Standard Item</li>
<li class="parent">Item with children
<ul>
<li>child item</li>
<li>child item</li>
<li class="parent">child item with children
<li>second level child</li>
<li>second level child</li>
</li>
<li>child item</li>
<li>child item</li>
</ul>
</li>
<li>Standard Item</li>
<li>Standard Item</li>
<li class="parent">Item with children
<ul>
<li>child item</li>
<li>child item</li>
<li class="parent">child item with children
<li>second level child</li>
<li>second level child</li>
</li>
<li>child item</li>
<li>child item</li>
</ul>
</li>
<li>Standard Item</li>
<li>Standard Item</li>
</ul>