Get Off My Lawn
Get Off My Lawn

Reputation: 36341

Stop click from firing on sub items

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.

Upvotes: 2

Views: 80

Answers (3)

Josh Crozier
Josh Crozier

Reputation: 241188

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();
  }
});

Upvotes: 2

Arg0n
Arg0n

Reputation: 8423

Check which target was clicked. e.target.

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

Upvotes: 2

user4276463
user4276463

Reputation:

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

Upvotes: 0

Related Questions