Stop click from firing on sub items

252
November 26, 2016, at 7:46 PM

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.

Answer 1

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

Check which target was clicked. e.target.

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

Answer 3

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

READ ALSO
DB operations with AJAX in MVC architecture [resolved]

DB operations with AJAX in MVC architecture [resolved]

I'm coding the backend of a project and in the module that I'm trying to implement I need to manage users, like, get all the data from the table Users and also get just the data relative to the selected user using an input text, for exampleIt also has to be able to update...

257
Jszip and jquery issue

Jszip and jquery issue

I want to realize zippingexe files from server, while somebody downloads files using checkboxes, but not the point

327
Access window.parent from embedded iframe

Access window.parent from embedded iframe

I already searched google, but I didn't find something useful

274