Just dipping my toes into the world of javascript and web development, I'm currently struggling to make my submenu's in the sidebar navigation area appear when clicked. Opening them individually with repetitive javascript felt clunky, so I'm searching for a better way (perhaps using a loop?). However, even after getting this far, I can't figure out how to close them back up efficiently. Here's a snippet of the HTML code I'm working with:
<ul id="sidebarNavUl">
<li class="sidebarLi">Main Topic:
<ul>
<li><a href="#">Sub Topic</a></li>
</ul>
</li>
<li class="sidebarLi">Main Topic:
<ul>
<li><a href="#">Sub Topic</a></li>
</ul>
</li>
<li class="sidebarLi">Main Topic:
<ul>
<li><a href="#">Sub Topic</a></li>
</ul>
</li>
</ul>
Here's a glimpse at my CSS as well:
.sidebarLi ul {
padding-left: 10px;
position: absolute;
right: 9000em;
}
.sidebarLi ul li a {
color: #003354;
}
.sidebarLi ul li a:hover {
color: #003354;
padding: 0 10px;
width: auto;
height: auto;
background-color: #edf3f6;
border-radius: 5px;
}
I'm starting with the submenus in an absolute position, planning to use javascript to toggle them between positions when clicked. However, my current script is far from ideal. If anyone could provide guidance on writing efficient javascript code to manage the submenu visibility, it would be greatly appreciated. Thank you.
In case you're curious, here's the flawed javascript attempt I made:
var mainSidebarLi = document.getElementsByClassName("sidebarLi");
mainSidebarLi[0].onclick = function () {
mainSidebarLi[0].getElementsByTagName("ul")[0].style.position = "static";
mainSidebarLi[0].getElementsByTagName("ul")[0].style.right = "0";
};
var mainSidebarLi = document.getElementsByClassName("sidebarLi");
mainSidebarLi[1].onclick = function () {
mainSidebarLi[1].getElementsByTagName("ul")[0].style.position = "static";
mainSidebarLi[1].getElementsByTagName("ul")[0].style.right = "0";
};
This process needs to be repeated for all elements in the li
array.