0

I have list items in an unordered list that are calling functions via jquery click events. The problem is the li is calling its function then calling the parent ul function. I just want the function called that I am referencing with the id. Is it a parent-child issue?

<ul id="mainlist">
  <li id="item1">list1</li>
  <li id="item2">list2</li>
</ul>

Jquery

$("#mainlist").click(function {
   someFunction();
  });
$("#item1").click(function {
  someOtherFunction();
 });

1 Answer 1

4

You simply have to stop the event from propagating to its ancestors:

$("#item1").click(function (event) {
  event.stopPropagation();
  someOtherFunction();
});

Or, you could check the clicked element (the event.target) to see if it's the <ul> or the <li> by checking its id property:

$("#mainlist").click(function (event) {
    switch (event.target.id) {
        case 'mainlist':
          someFunction();
          break;
        case 'item1':
          someOtherFunction();
          break;
        default:
          break;
    }
});

References:

Sign up to request clarification or add additional context in comments.

2 Comments

I checked the documentation and tried the return false option and this works too.
I'm glad to have helped! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.