user2585299
user2585299

Reputation: 883

Hiding css dropdown menu on hover

In the navigation bar, on click of "Home 3" menu, a dropdown menu appears through jQuery. I want to hide this menu when I hover on other links of the menu for which I have included style as below:

.nav-ul .menu-item:hover ul{
    display:none;
}

Here is the fiddle: http://jsfiddle.net/Tw44R/1/

Upvotes: 0

Views: 1524

Answers (4)

T J
T J

Reputation: 43156

The selector .nav-ul .menu-item:hover ul will only target the <ul> inside the .menu-item item being hovered.

You can't traverse up the DOM using CSS as of now.

Add the following script:

$('.menu-item').hover(function(){
    $(this).siblings().find('ul').hide();
});

Demo

Update:

If you want to hide the dropdown when the mouse moves away, you can use the second callback of hover, as given below:

$('.menu-item').hover(function () {
    $(this).siblings().find('ul').hide();
},

function () {
    $(this).find('ul').hide()
});

Demo

Side note: For anyone down voting seeing Yury Tarabanko's comment, it's not a reliable solution for the task at hand (it doesn't work if the submenu is before the hovered item).

Upvotes: 1

Bla...
Bla...

Reputation: 7288

You can use this approach:

$(".nav-header .nav-ul .menu-item").hover(function (){
        $(".menu-item").each(function(){
            if($(this).find("ul").css("display") == "block")
                $(this).find("ul").css("display","none");
        });
    })

Check out this JSFiddle..

EDIT: I shouldn't used .menu-item-link, just edited the JSFiddle too. Everything works fine.. Thank you for pointing out my mistake..

Upvotes: 1

Puzzled
Puzzled

Reputation: 74

This solution will open the sub-menu with a click and close the sub-menu when you move away from either the header or the sub-menu.

I gave each header item an id

<li class="menu-item" id="3">

Then:

$(function(){
   $("#3").click(function(){
     $(".nav-ul .menu-item ul").css('display', 'block');
   });
   $("#3").mouseleave(function(){
     $(".nav-ul .menu-item ul").css('display', 'none');
   });
});

Check it out:

http://jsfiddle.net/Tw44R/20/

Upvotes: 1

Jai
Jai

Reputation: 74738

Try with jQuery's mouseenter:

$(function () {
    $(".nav-header .nav-ul .menu-item .menu-item-link").click(function (link) {
        if (link.currentTarget.text === 'Home 3') {
            $(this).next("ul").css('display', 'block');
        }
        link.stopPropagation();
    }).mouseenter(function () {
        $(".nav-header .nav-ul .menu-item ul:visible").css('display', 'none');
    });
});

Demo

Upvotes: 1

Related Questions