0

I have a simple drop down menu. When you click .drop-down, a sub menu slides down. However, if you click any of the children of .drop-down, it slides back up again. I want only the .drop-down that was clicked to slide the menu, none of the its descendents.

Here it is in action: http://jsfiddle.net/tmyie/uXn5k/2/

<ul>
    <li class="drop-down">
        <a href="#"> Main </a> 
        <ul class="sub-menu">
          <li><a href="#">Sub</a> </li>
          <li><a href="#">Sub</a> </li>
          <li><a href="#">Sub</a> </li>
        </ul>
    </li>
    <li><a href="#">Main</a> </li>
    <li><a href="#">Main</a> </li>
    <li><a href="#">Main</a> </li>
    <li><a href="#">Main</a> </li>
</ul>

jQuery

$( ".drop-down" ).click(function() {
  $('.sub-menu').slideToggle();
});

$('.drop-down').fadeTo('slow', 0.3);

http://jsfiddle.net/tmyie/uXn5k/2/

1 Answers1

2

Target the a specifically

$( ".drop-down>a" ).click(function() {
  $('.sub-menu').slideToggle();
});

$('.drop-down').fadeTo('slow', 0.3);

Or, just move the class from the li to the a

<ul>
    <li>
        <a href="#" class="drop-down"> Main </a> 
        <ul class="sub-menu">
        <li><a href="#">Sub</a> </li>
        <li><a href="#">Sub</a> </li>
        <li><a href="#">Sub</a> </li>
    </ul></li>
    <li><a href="#">Main</a> </li>
    <li><a href="#">Main</a> </li>
    <li><a href="#">Main</a> </li>
    <li><a href="#">Main</a> </li>
</ul>

EDIT:

By the way, you're going to run into trouble with multiple dropdowns using this script. Consider making the following changes:

   $( ".drop-down>a" ).on("click", function() {
      $(this).siblings('.sub-menu').slideToggle();
    });

    $('.drop-down').fadeTo('slow', 0.3);

http://jsfiddle.net/uXn5k/6/

Calvin
  • 630
  • 3
  • 17
  • I'd love to, however this is a simplified process of the WordPress default navigation. I'm a little limited to the classes I can apply, and to where. :( –  Nov 07 '13 at 14:31
  • @tmyie Have a look at my other edit as well. If you're planning on using more than one drop-down anyway. – Calvin Nov 07 '13 at 14:38
  • Thanks. How come targeting the `a` specifically fixed this? –  Nov 07 '13 at 14:39
  • 2
    @tmyie because you bound the click event handler to `.drop-down` - so anywhere you click inside that element will trigger the event - which are all the descendant elements are inside the `.drop-down` element.. When you get more specific and bind only the anchor - only clicking inside the anchor will trigger the event – wirey00 Nov 07 '13 at 14:43