Splat ty
Splat ty

Reputation: 41

Get class name of child element on mouseover jquery

When hovering over the menuItem list i want the subMenu to display then mouseout hide again. Question is how do i target the specific subMenu (assuming i'll have more menu items with submenus) within the menuItem clicked.

html

<ul>
 <li class="menuItem">
 Menu Item 1
 <ul class="subMenu">
 <li> <a href="#"> Link 1 </a> </li>
 <li> <a href="#"> Link 2 </a> </li>
 </ul>
</li>

javascript

$(document).ready(function() {
$('.menuItem').mouseover(function() {


$($this).class('.subMenu').show();

});
});

Upvotes: 0

Views: 5826

Answers (3)

Frederik Wordenskjold
Frederik Wordenskjold

Reputation: 10221

A slightly different version of David Thomas' solution, which uses toggle() and only one inner function:

$('.menuItem').hover(function(){
    $(this).find('.subMenu').toggle();
});

Since you just want to show or hide .subMenu, you only need one inner function, which is called on mouse-over and mouse-leave. It's probably a matter of personal preference if you like to explicitly write the mouse-leave function, but I like this shorter version.

Upvotes: 2

David Thomas
David Thomas

Reputation: 253358

Try:

$('.menuItem').hover(
    function(){
        // first function is for the mouseover/mouseenter events
        $(this).find('.subMenu').show();
    },
    function(){
        // second function is for mouseleave/mouseout events
        $(this).find('.subMenu').hide();
    });

JS Fiddle demo.

It's worth pointing out that you don't need to use JavaScript at all for this (unless you're having to support browsers such as IE6 and below), and could use just CSS:

.menuItem:hover .subMenu,
.subMenu:hover {
    display: list-item;
}
.subMenu {
    display: none;
}​

JS Fiddle demo.

References:

Upvotes: 4

Engineer
Engineer

Reputation: 48793

Use:

$(this).find('.subMenu').show();

instead of:

$($this).class('.subMenu').show();

Upvotes: 0

Related Questions