2

I have html that looks like this:

<ul>
    <li class="database">Item One
        <ul>
            <li>Sub One</li>
            <li>Sub Two</li>
            <li>Sub Three</li>
        </ul>
    </li>
    <li class="database">Item Two
        <ul>
            <li>Sub One</li>
            <li>Sub Two</li>
            <li>Sub Three</li>
        </ul>
    </li>
<ul>

I then created this JavaScript to hide/show the sub list when clicked.

$(document).on('click', 'li.database', function (e) {
    e.stopPropagation();
    $(this).children('ul').children('li').toggle();
});

It works, but it hides the list no matter if I click on the submenu or not. How can I hide the items only when the root li is clicked? I would like to eventually have the sub items have their own events when clicked.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

3 Answers3

2

Check which target was clicked. e.target.

Use e.stopPropagation() in the click events for the sub-items instead.

Arg0n
  • 8,283
  • 2
  • 21
  • 38
2

You can check to see if e.target is the same as e.currentTarget.

This works because e.target is the element that fired the event, and e.currentTarget is the element that the event listener is attached to.

Example Here

$(document).on('click', 'li.database', function (e) {
  if (e.target === e.currentTarget) {
    $(this).children('ul').children('li').toggle();
  }
});
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
0

Try creating an id tag and reference that rather than the class name. That way you can separate the databases by id.