In my recent project, I have implemented a vertical menu with a feature that displays the sub-items when the parent item is hovered over. The structure of the HTML code looks like this:
<ul id="nav">
<li><a href="#">Continents</a>
<ul>
<li><a href="#">Europe</a>
<ul>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ul>
</li>
<li><a href="#">Asia</a>
<ul>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ul>
</li>
<li><a href="#">Africa</a>
<ul>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Places</a>
<ul>
<li><a href="#">Place1</a></li>
<li><a href="#">Place2</a></li>
</ul>
</li>
<li><a href="#">Oceans</a>
<ul>
<li><a href="#">Pacific</a></li>
<li><a href="#">Atlantic</a></li>
</ul>
</li>
</ul>
By default, only nav li
elements are visible. However, once a user hovers on nav li a
, the subsequent child elements are displayed. This functionality worked perfectly when there was only one ul
under the initial li
elements. But now, with the 2nd nested ul
in the 1st li
branch, it presents a challenge.
Below is the Javascript code I used:
<script type="text/javascript">
$(document).ready(function () {
$('#nav > li > a').hover(function(){
if ($(this).attr('class') != 'active'){
$('#nav li ul').slideUp();
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
$(this).addClass('active');
}
});
});
</script>