1

I'm trying to use show/hide on a submenu. It looks like this:

  1. Parent 1
  2. Parent 2
    1. Child A
    2. Child B
  3. Parent 3
    1. Child C
    2. Child D

I only want to show the submenu when I click on its parent. Currently, whenever I click on any parent, I get all of the submenus.

Like so: http://jsfiddle.net/saltcod/z7Zgw/

Also, clicking on a link in the submenu toggles the menu back up.

2 Answers 2

4
//select all the `<li>` element that are children of the `.parent` element
$('.parent').children().click(function(){
    
    //now find the `.child` elements that are direct children of the clicked `<li>` and toggle it into or out-of-view
    $(this).children('.child').slideToggle('slow');     
});

Demo: http://jsfiddle.net/jasper/z7Zgw/1/

Basically the code above uses this to reference the clicked <li> element so we can find the .child element that is a child of the clicked <li> element.

This: $('.child')

Changed to: $(this).children('.child')

Update

Also you can stop the propagation of the click event on the nested .child elements like this:

$('.parent').children().click(function(){
    $(this).children('.child').slideToggle('slow');

//select all the `.child` elements and stop the propagation of click events on the elements
}).children('.child').click(function (event) {
    event.stopPropagation();
});

Demo: http://jsfiddle.net/jasper/z7Zgw/9/

Docs:

1
2

Your code was:

$('.parent li').click(function(){
    event.preventDefault();
    $('.child').slideToggle('slow');
});

$('.child') selects all the "children". Change it to $('.child', this), to select only the ones inside the current element.

The click event bubbles, so in order to ensure that only clicking the parent itself toggles the state, you can compare the event.target with this.

However, this is quicker:

$('.parent > li > a').click(function(){
    event.preventDefault();
    $(this).parent().find('.child').slideToggle('slow');
});

See fiddle

EDIT as @Jasper pointed out, this is shorter/quicker:

$('.parent > li > a').click(function(){
    event.preventDefault();
    $(this).siblings('.child').slideToggle('slow');
});
3
  • .parent().find('.child') could also be .siblings('.child') or a faster selector would be .next() since the .child elements appear to come directly after the a elements.
    – Jasper
    Feb 27, 2012 at 18:10
  • You're right, of course. I changed the script twice (once for each problem the OP asked about), and missed that.
    – ori
    Feb 27, 2012 at 18:11
  • Thanks a lot guys. I went with the .siblings() approach. Short, simple and to the point. Plus, I thought the odds of me remembering stopPropagation() the next time were pretty slim =). Thanks a lot.
    – saltcod
    Feb 27, 2012 at 18:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.