0

im trying to animate only the first-level li of this (here shortened) menu:

<div class="test">
    <ul id='nav'>
        <li>Start</li>
        <li>Basics
            <ul>
                <li class="level_2">Installation</li>
                <li><a href="#">Syntax</a></li>
                <li>Selektoren</li>
                <li>Events und Ereignisse</li>
                <li>Zusammenfassung</li>
            </ul>
        </li>
    </ul>
</div>

Here's a jsfiddle: https://jsfiddle.net/kfc79z6h/4/

So I want the menu to slideUp/Down only when clicking on "Basics", "Effekte", "HTML", "Traversing".

As you can see in the fiddle, I've tried out a lot of answers I've found so far, but nothing seems to work.

I hope you can help :)

ovih
  • 27
  • 3

3 Answers3

2

Since JS events bubble upward in the DOM, the click event will eventually fire on the parent, even though the actual click happened on a child <li>. The easiest way to only accept direct clicks on the actual element is to check what element event.target is, as such:

$("#nav > li").on( "click" , function(event){
  if (event.target !== this) { return; }
  // ...
}

Here's an updated fiddle.

https://jsfiddle.net/rzkw9ce2/

For more information on JS event propagation, read Arun's excellent answer to this post:

What is event bubbling and capturing?

Community
  • 1
  • 1
Nicklas Nygren
  • 2,595
  • 13
  • 19
0

I've updated the fiddle for you

fiddle

It's simplier and cleaner if you use a class for li elements you want to trigger click.

For example:

$('.accordion').click(function(){
 // something
})

If you want your click event only for elements with .accordion class check if current clicked element is one from click event targets

if(e.target !== this)  return; 
Cosmin
  • 2,184
  • 21
  • 38
0

JavaScript events move up through the Document Object Model (DOM). When you click on child, the click event moves up to the parent, even though you clicked on the <li>. To get a direct click, check which item was clicked by using event.target:

$("#nav > li").on("click", function(event) {
   if (event.target !== this) { return; }
   //blah blah here
}