Reputation: 477
I have a menu which I have working fine but I need a small change and that is I need the parent menu to toggle the submenu, currently if you click the parent menu the submenu appears but I need it so when you click the parent menu again it closes the sub menu.
You can see the menu in action here.
and this is the javascript that is for the menu:
$('.dropdown-toggle').click(function() {
$('.dropdown').css('display', 'none'); // Hide submenus when other submenus are clicked
$(this).next('.dropdown').toggle();
});
$(document).click(function(e) {
var target = e.target;
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').hide();
}
});
This is the menu html
<nav class="main">
<a class="dropdown-toggle" href="#" title="Menu">Menu One</a>
<ul class="dropdown">
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Search</a></li>
</ul>
</nav>
Upvotes: 1
Views: 2038
Reputation: 9
This can be done easily with Bootstrap:
<li class="submenu">
<i class="la la-user"></i>
<span> Main menue </span>
<span class="menu-arrow"></span>
<ul style="display: none;">
<li><a href="#">sub menu 1</a></li>
<li><a href="#"> sub menu 2 </a></li>
<li><a href="#"> sub menu 3 </a></li>
</ul>
</li>
Upvotes: 0
Reputation: 919
I think this code will be enough.
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown').toggle();
});
Upvotes: 0
Reputation: 57
I think this is the simplier way :) Hope you helped
$(".dropdown").css('display', 'none');
$('.dropdown-toggle').click(function(e) {
if ($(this).next().is(":visible")){
$(this).next().hide();
}else{
$(".dropdown").hide();
$(this).next().show();
}
});
a {
display: block;
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script><nav class="main">
<nav>
<a class="dropdown-toggle" href="#" title="Menu">Menu One</a>
<ul class="dropdown">
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Search</a></li>
</ul>
<a class="dropdown-toggle" href="#" title="Menu">Menu One</a>
<ul class="dropdown">
<li><a href="#">Menu Item</a></li>
<li><a href="#">Menu</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Search</a></li>
</ul>
</nav>
Upvotes: 0
Reputation: 1525
Replace this code:
$('.dropdown-toggle').click(function() {
$('.dropdown').css('display', 'none'); // Hide submenus when other submenus are clicked
$(this).next('.dropdown').toggle();
});
With the code below:
$('.dropdown-toggle').click(function() {
var $currentDropdown = $(this).next('.dropdown');
$currentDropdown.siblings('.dropdown').not($currentDropdown).removeClass('toggled');
$currentDropdown.siblings('.dropdown').not($currentDropdown).hide();
$currentDropdown.toggleClass('toggled');
$currentDropdown.toggle();
});
That should do it.
Upvotes: 1