0

I'm trying to create a clickable sub-menu with slideDown() via jQuery. However - hover() is working as intended, but click() doesn't do anything.

Here's my jQuery:

$("#n_ulist li").click(function(){
    $("ul", this).stop().slideDown(500);
    },
    function() {
    $("ul", this).stop().slideUp(500);  
});

What is wrong here?

Jenz
  • 8,280
  • 7
  • 44
  • 77
daftpanda
  • 5
  • 1
  • 1
    [.click](http://api.jquery.com/click/) doesn't allow two functions - are you thinking of [.hover](http://api.jquery.com/hover/) – Pete Sep 03 '14 at 08:57
  • and how am I supposed to slideUp the dropdown when clicking another list element? - sorry I'm new to this :( – daftpanda Sep 03 '14 at 08:58
  • You would need to add something like `$(this).parent().find('ul').stop().slideUp(500);` in the same click function (before your slideDown) - or if your menu is more than one level `$('#n_ulist').find('ul').stop().slideUp(500);` – Pete Sep 03 '14 at 09:01

3 Answers3

0

The click() function takes only one callback as its argument, so always your first callback slideDown(500); gets executed....

You can use slideToggle()

$("#n_ulist li").click(function () {
    $("ul", this).stop().slideToggle(500);
});

The hover() takes 2 callbacks as arguments, 1 for mouseenter and another for mouseleave. There were a toggle() version which was doing the same for click event but it was removed in jQuery 1.9.

If you want a plugin which will allow you to do the same look at this toggleClick() implementation.

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

May be by using .slideToggle() .

wooer
  • 1,677
  • 2
  • 16
  • 27
0

try the following instead:

$("#n_ulist li").click(function(){
    $(this).parent().find('ul').stop().slideUp(500);
    $("ul", this).stop().slideDown(500);
});

or if your menu is more than one level you may need to use

$('#n_ulist').find('ul').stop().slideUp(500);

EDIT

As per your comments

$("#n_ulist li").click(function(){
    $(this).parent().find('ul').stop().slideUp(500);
    $("ul", this).stop().slideToggle(500).click(function(e) {
        e.stopPropagation();
    });
});
Pete
  • 57,112
  • 28
  • 117
  • 166
  • 1
    that worked fine, thanks ;) but is there a way to accomplish the same effect when I click on the parent element again to close(`slideUp()`) the submenu? So I want to slide-up the submenu when I click on the same element and when I click another parent element... – daftpanda Sep 03 '14 at 09:09
  • change the `slideDown` to `slideToggle` – Pete Sep 03 '14 at 09:11
  • well I got a problem now - if I click any object in the submenu, the list slides up too...that is not intended...any ideas? – daftpanda Sep 03 '14 at 12:39
  • see edit above - you need to stop the event propagating when you click on the child – Pete Sep 03 '14 at 12:48