I have this vertical menu:
<li class="vertical_menu_group_item orange" id="verticalMenu"><a class="mx-3" >Menu item</a>
<ul style="display:none" class="submenus">
<li><a href="">Sub menu item 1</a></li>
<li><a href="">Sub menu item 2</a></li>
</ul>
</li>
And as you can see I have set the display:none
for the class submenus
and then within this Javascript code I tried to show the sub menu items, when user click on the menu item
:
$(document).on('click','#verticalMenu',function(){
let sbm = document.querySelector(".submenus");
sbm.style.display = "block";
});
But now this thing does not work out and not shows the sub menu items.
However, I have made sure that the onlick event runs successfully.
I also tried showing the sub menu items like this:
sbm.toggle();
But it says: toggle is not a function
So what’s going wrong here? How can I properly hide/show this .submneus
class when clicking on the link with id of verticalMenu
?
3
Answers
You are not removing the display block, therefore it will always be shown as soon as you clicked it once. You have to change the display to none again after your first click.
A more elegant solution is the correct implementation of the toggle function from jquery. I have also styled the cursor for your menu element so there is a visible response when the cursor is on it.
See https://api.jquery.com/toggle/ for more infos.
Here Try This Its Working
When you use
display:none
under<ul>
tag it completely removes the element in the dom. So when You Inspect it on browser you can’t see the code there as it is non existence. Because of thattoggle()
is not working as the element doesn’t exist in DOM and not getting class. That’s the reason why it says "toggle is not a function". So instead of usingdisplay
property, usevisibility
instead.Also set the height to 0px to remove space when using visibility:"hidden" property and height:"auto" when you want to show it.