Reputation: 3488
I am trying to achieve a simple drop-down menu with the following HTML structure. This structure is mandatory (I think) as explained in the illustrations below.
<nav role="navigation">
<ul id="main-menu" class="nav top-nav clearfix">
<li id="menu-item-1" class="menu-item"><a href="#">Menu 1</a></li>
<li id="menu-item-2" class="menu-item"><a href="#">Menu 2</a></li>
<li id="menu-item-3" class="menu-item"><a href="#">Menu 3</a></li>
</ul>
<ul id="sub-menu-1" class="sub-menu nav clearfix">
<li class="menu-item"><a href="#">Sub Menu 1.1</a></li>
<li class="menu-item"><a href="#">Sub Menu 1.2</a></li>
<li class="menu-item"><a href="#">Sub Menu 1.3/a></li>
</ul>
<ul id="sub-menu-2" class="sub-menu nav clearfix">
<li class="menu-item"><a href="#">Sub Menu 2.1</a></li>
<li class="menu-item"><a href="#">Sub Menu 2.2</a></li>
<li class="menu-item"><a href="#">Sub Menu 2.3/a></li>
</ul>
</nav>
To get a better idea of what I am trying to achieve I've made the following illustrations:
<ul><li><ul></ul></li></ul>
would do. As you can see the submenu has to scale to 100% of the container and has all the items arranged in center.I think the best approach is with javascript (not sure you can do this with only CSS), but I am kind off stuck. The sub menu appears on main menu item hover, but as soon as I hover out into the sub menu in order to navigate, the sub menu disappears. Anyway, this is the javascript:
$('nav #main-menu .menu-item a').hover(
function() {
var id = $(this).parent().attr('id');
id = id.substr(id.length - 1);
submenu = $('#sub-menu-' + id);
submenu.show();
},
function() {
var id = $(this).parent().attr('id');
id = id.substr(id.length - 1);
submenu = $('#sub-menu-' + id);
submenu.hide();
}
);
I am pretty sure that there is a better way to do this.
I've also set up a FIDDLE for better understanding.
Upvotes: 0
Views: 199
Reputation: 1381
//show sub menu when we hover over an item
$('nav #main-menu > .menu-item')
.on('mouseenter', function() {
$('.sub-menu').hide();
var id = $(this).attr('id');
id = id.substr(id.length - 1);
$('#sub-menu-' + id).show();
});
//hide submenu when the mouse goes away
$('nav').on('mouseleave', function() { $('.sub-menu').hide(); });
Modified your fiddle here: http://jsfiddle.net/3z8MR/10/
Edit Add this line to conform to your specs in the comments
$('.sub-menu').on('mouseleave', function() { $(this).hide(); });
Upvotes: 1