javascriptjqueryjquery-eventsjquery-click-event

How to get the clicked child list item only with jQuery?


I have a multi-level unordered list. I am trying to attach the click handler to the list item and when it's clicked, I am trying to add the class active to it, but when a sub list item is clicked, the click handler is being triggered for both sub and it's parent, I think it's because it has of the same element li in all levels. How can I just attach the event to a certain level only?

Here is a sample of code, but click on the jsfiddle to see it in action:

HTML MARKUP

<ul>
  <li>test</li>
  <li>test
    <ul>
      <li>test</li>
      <li>test
    <ul></li>
  <li>test</li>
  <li>test</li>
</li>
<li>test</li>
<li>test</li>
</ul>

JAVASCRIPT

$("li").click(multiLevelClickHandler);
function multiLevelClickHandler(event)
{
    event.preventDefault();
    var $this = $(this);
    console.log($this);
    var $actives = $this.siblings().find(".active");

    if($actives.length > 0){
        $actives.removeClass('active');
        setTimeout(function(){
            $this.addClass('active');
        }, 250);
    } else {
        $this.addClass('active');
    }
}

Here is JsFiddle: http://jsfiddle.net/zcLzA/

I tried attaching the click handlers individually to each level of list items, but it's always get attached to the parent as well as the clicked list item.


Solution

  • Use event.stopPropagation();:

    function multiLevelClickHandler(event){
        event.stopPropagation();
    

    This stops the event from bubbling up the DOM.

    http://jsfiddle.net/zcLzA/2/

    ref: http://api.jquery.com/event.stoppropagation/