0

I am trying to make a menu where if a user hovers on 'menuItem' it will only show the submenu for that specific element.

I know you can use $(this) but in the jQuery when i change

$(subMenu).removeClass("hide-submenu").addClass("show-submenu");

to

$(this).removeClass("hide-submenu").addClass("show-submenu");

It doesnt seem to work

var menuItem = $("nav > ul > li > a");

var subMenu = $("ul > li > ul");


$(subMenu).addClass("hide-submenu");

$(menuItem).hover(function(){
if($(subMenu).hasClass("hide-submenu")) {
        $(subMenu).removeClass("hide-submenu").addClass("show-submenu");
}
else {
        $(subMenu).removeClass("show-submenu").addClass("hide-submenu");
}
});

Below is my HTML

<nav>
    <ul>
        <li>
            <a>MENU ITEM</a>
                <ul>
                    <li><a href="#">SUB ITEM 1</a></li>
                    <li><a href="#">SUB ITEM 2</a></li>
                    <li><a href="#">SUB ITEM 3</a></li>
                </ul>
        </li>

    </ul>
</nav>
3
  • Try unchaining the methods Commented Jul 26, 2013 at 11:10
  • 2
    In you hover callback this would be your menuItem not subMenu Commented Jul 26, 2013 at 11:13
  • You can use an jQuery toggle function, this will save you a few lines of coding. Commented Jul 26, 2013 at 11:15

4 Answers 4

1

Because $(this) contains $(menuItem) as Event is being called on $(menuItem).

Sign up to request clarification or add additional context in comments.

Comments

0

In your code when you hover inside the $(menuItem) then when you use this, it refers to the $(menuItem) not to the $(subMenu). Hence you can not use this here like you wanted to use it. Instead you can do this:

menuItem.hover(function () {

    // Go to the next sibling `ul` in the current scope, using `this`
    var $next = $(this).next('ul');  

    if ($next.hasClass("hide-submenu")) {
        $next.removeClass("hide-submenu").addClass("show-submenu");
    } else {
        $next.removeClass("show-submenu").addClass("hide-submenu");
    }
});

One more thing:

var menuItem = $("nav > ul > li > a");

menuItem is already a jQuery object here, you don't need to do $(menuItem) again. Same goes for the subMenu.

Comments

0

Use,

var menuItem = $("nav ul li a");
var subMenu = $("ul li ul");

instead of

var menuItem = $("nav > ul > li > a");
var subMenu = $("ul > li > ul");

Comments

0

You may want

$("ul > li > ul").addClass("hide-submenu");

var menuItem = $("nav > ul > li");
menuItem.hover(function(){
    $(this).children('ul').removeClass("hide-submenu").addClass("show-submenu");
}, function(){
    $(this).children('ul').removeClass("show-submenu").addClass("hide-submenu");
});

Demo: Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.