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?
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.
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.
stopPropagation()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
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.
Use event.stopPropagation()
; the link provides an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With