Question

I have a navigation with list items containing "a" tags. One of the list item has a submenu which should be displayed on hover or click of the parent list item. How to toggle this using jquery?

Était-ce utile?

La solution

On hover

First in css you need to hide sub menu, like this

css

ul li ul{
    display:none;
}

js

$('ul li').hover(function(){
    $('ul',this).css('display','block');
},function(){
    $('ul',this).css('display','none');
});

.hover(first parameter, [second parameter]) first parameter take mouse in and second take mouse out which is optional. For both parameters we have created anonymous function.


on Click

use toggleClass like this

js

$('ul li').click(function() {
    $('ul',this).toggleClass( 'showSubmenu');
});

css

.showSubmenu{
    display:block;
}

Note

You need to put class on ul or wrap ul in div with class and then target in jquery with that class otherwise it will be applied to all ul li on web page.

Autres conseils

This should get you going with .click as someone else gave you a way to get it working with hover. Here's a fiddle: http://jsfiddle.net/v6X7x/1/

(take a look at the html in the fiddle)

Hide the second level menu items with css:

.layer2 {
    display: none;
}

And finally add a jQuery click event handler which first checks if there is a .layer2, then toggles if there is:

$(".layer1 li").click(function() {
    var num = $(this).find("ul.layer2").length;
    if (num > 0) {
        jQuery(this).children("ul.layer2").slideToggle();
    }
});

FYI: you'll probably get better answers if you put some of what you've already done in the question.

Working example: http://jsfiddle.net/awesome/y924G/

The below code provides .toggle(), .click() and .hover() events on the same a-tag as specified in the question.

JavaScript:

$dm = $('.dropdown-menu');
$('.dropdown').hover(
  function () {
    $dm.show();
  }, function () {
    $dm.hide();
}).click(function () {
    $dm.toggle();
});
$dm.hover(
  function () {
    $dm.show();
  }, function () {
    $dm.hide();
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top