Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent jQuery events from bubbling up to parent elements?

I have a series of nested UL's that are like this:

<ul class="categorySelect" id="">
  <li class="selected">Root<span class='catID'>1</span>
    <ul class="" id="">
      <li>First Cat<span class='catID'>2</span>
        <ul class="" id="">
          <li>cat in First<span class='catID'>3</span>
            <ul class="" id="">
            </ul>
          </li>
          <li>another cat in first<span class='catID'>4</span>
            <ul class="" id="">
            </ul>
          </li>
        </ul>
      </li>
      <li>cat in root<span class='catID'>5</span>
        <ul class="" id="">
        </ul>
      </li>
    </ul>
  </li>
</ul>

I then have jQuery that I intended to move the "selected" class to different LIs on click():

$(document).ready(function () {

    $("ul.categorySelect li").click(function () {
        $("ul.categorySelect li.selected").removeClass("selected");
        $(this).addClass("selected");
    })

});

When I tested this, at first it didn't appear to be working at all. I added an alert("click") inside the click event function and I was able to tell that it was working, but the click event registered on both the child LI and parent LIs which meant that ultimately the root LI would always end up as selected.

Is there a way to prevent the click() event from executing on parent LIs?

like image 634
quakkels Avatar asked Nov 19 '10 18:11

quakkels


People also ask

How do I stop jQuery from bubbling?

The event. stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.

How can you stop the event bubbling up?

If you want to stop the event bubbling, this can be achieved by the use of the event. stopPropagation() method. If you want to stop the event flow from event target to top element in DOM, event. stopPropagation() method stops the event to travel to the bottom to top.

Which methods prevent the event from bubbling up the DOM tree preventing any parent handlers from being notified of the event?

stopPropagation()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

How does jQuery handle event bubbling?

The concept of "bubbling up" is like if you have a child element with a click event and you don't want it to trigger the click event of the parent. You could use event. stopPropagation() . event.


1 Answers

Use event.stopPropagation(); the link provides an example.

like image 58
sushil bharwani Avatar answered Sep 25 '22 06:09

sushil bharwani