Reputation: 5402
I am creating a menu that will be several layers deep. My intention is to use several nested UL and LI elements to make this structure. When I mouse over one of the LI elements it shows the next level of navigation for that menu item. When I try to move my mouse to that element, however, it automatically shows me the children of the final menu item.
<div class="menu">
<ul>
<li><a>First</a>
<ul>
<li><a>Child of First</a></li>
<li><a>Child of First</a></li>
</ul>
</li>
<li><a>Second</a>
<ul>
<li><a>Child of Second</a></li>
<li><a>Child of Second</a></li>
</ul>
</li>
</ul>
</div>
<style>
.headerMenu ul {
list-style: none;
padding: 0;
margin: 0;
width: 50%;
background: black;
color: white;
}
.headerMenu ul ul {
position: absolute;
top: 0;
width: 0;
left: 50%;
opacity: 0;
}
.headerMenu ul ul.visibleSub {
width: 100%;
opacity: 1;
}
</style>
<script>
$(document).ready(function () {
var $ul = $('.headerMenu ul');
$ul.find('li').on({
mouseenter: function() {
$(this).find('ul').first().addClass('visibleSub');
},
mouseleave: function() {
$(this).find('ul').first().removeClass('visibleSub');
}
});
});
</script>
You can see and demo the very stripped down code at https://codepen.io/pcasagrande/pen/RZqQwO
Upvotes: 0
Views: 455
Reputation: 382
If you don't need animation, you can use display: hidden
instead of opacity: 0
Because in your code, although the second level li a
links are not visible, they have padding/margin and actually occupies space on the right side of the first level ul
.
https://codepen.io/anon/pen/prQapW
Upvotes: 1
Reputation: 167
Just add z-index: -1 for unvisible ul:
.menu ul ul {
position: absolute;
top: 0;
width: 0;
left: 50%;
opacity: 0;
z-index: -1;
}
.menu ul li:hover > ul{
opacity: 1;
width: 100%;
z-index: 1;
}
Also as I mention above you can avoid jquery and do this with pure css.
Also you can add some transition for .menu ul ul{ transition: .2s}
and it will have sime kind of simple animation.
Upvotes: 1
Reputation: 16741
It is the fact you use opacity
to hide the second layer of menu's. They are still there, and you hover over the second set when you move there, so it's made visible. If you use display
to really hide the second layer it will work. Change your CSS to:
.menu ul {
list-style: none;
padding: 0;
margin: 0;
width: 50%;
background: black;
color: white;
}
.menu ul ul {
display: none;
position: absolute;
top: 0;
width: 0;
left: 50%;
}
.menu ul ul.visibleSub {
width: 100%;
display: block;
}
Nothing else needs to change.
Upvotes: 1