I have implemented a dropdown menu with a secondary dropdown inside it. By incorporating JQuery code, I have enabled the functionality to open and close both dropdowns when hovering.
As I hover over the primary dropdown labeled services
and proceed to hover over service2
, which is the secondary dropdown, I encounter an issue where the dropdown closes as I try to access the elements within it such as Service2 sub1
and Service2 sub2
.
Below is the code snippet:
HTML:
<div class="navbar navbar-default navbar-static-top">
<div class="container">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">Services <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Service1</a></li>
<li role="presentation">
<a data-toggle="collapse" href="#collapse" class="sub-menu">
Service2 <b class="caret"></b>
</a></li>
<ul>
<div id="collapse" class="panel-collapse collapse">
<li role="presentation"><a href="#">Service2 sub1</a></li>
<li role="presentation"><a href="#">Service2 sub2</a></li>
</div>
</ul>
</ul>
</li> <!-- .dropdown -->
</ul> <!-- .navbar-nav -->
</div> <!-- .container -->
</div> <!-- .navbar -->
JQuery:
$(document).ready(function() {
//Stop propagation for the dropdown
$(document).on('click', '.dropdown-menu', function (e) {
e.stopPropagation();
});
//Hover function for the main menu 'Services'
$(".dropdown").hover(
function() {
$('.dropdown-menu', this).stop().fadeIn("fast");
$(this).addClass('active');
},
function() {
$('.dropdown-menu', this).stop().fadeOut("fast");
$(this).removeClass('active');
}
);
//Hover function for the sub-menu `Services`
$(".sub-menu").hover(
function() {
$('#collapse').removeClass('collapse').addClass('collapse in');
},
function() {
$('#collapse').removeClass('collapse in').addClass('collapse');
}
);
});
Feel free to test the functionality using this live fiddle: https://jsfiddle.net/0ksz9tnL/