yeomandev
yeomandev

Reputation: 11806

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?

Upvotes: 5

Views: 4096

Answers (1)

sushil bharwani
sushil bharwani

Reputation: 30197

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

Upvotes: 8

Related Questions