rakop rakop - 1 year ago 58
Javascript Question

how to show/hide when hover in/out on specific elemet

I make a secondary menu and I like it to be displayed when user hover a specific one of the main menu items....

I tried this code but it didn't work...

.second-menu {display:none}
ul li #2:hover + .second-menu {display:block}

<li id="1">first</li>
<li id="2">second</li>
<li id="3">third</li>

<div class="second-menu">

any suggestions?....
only by css or javascript....

Thank you in advance!!!

Answer Source

If you wish to use CSS, you will have to put your sub menu inside the element that you want to hover.

For the CSS, C.Raf.T's answer is perfect.

If for some reason you want to use javascript you could do something like this

document.getElementById('2').addEventListener('mouseenter', function ()
  document.getElementById('subMenu').style.display = "block";
document.getElementById('2').addEventListener('mouseleave', function ()
  document.getElementById('subMenu').style.display = "none";

Note: the above code requires you to add a "subMenu" id to the div containing your menu. If you wish to display serval menus with only one hover event, use a class instead.

But honestly, the CSS answer is the best way to go if all you need is nested sub menus. If the sub menu has to be outside of the parent, you will need the javascript.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download