views:

33

answers:

3

I was creating a tree using UL LI list and jQuery. I used a jQuery Selector

jQuery(li:has(ul)) to find all the list nodes having childs and then added a click event to it.

jQuery(li:has(ul)).click(function(event) {

    jQuery(this).children.toggle();
    jQuery(this).css("cursor","hand");

});

This works for me except i dont understand why i get a cursor hand and click event triggering even when i take mouse pointer to childs of my selected li


<li> Parent // it works here that is fine
<ul>
<li> child1   // it works here i dont understand need explanation
</li>
<li> child2   // it works here i dont understand need explanation
</li>
</ul>
</li>

+2  A: 

The cursor property and the click event are inherited by the element's children.

To prevent the cursor property from being inherited, you can add a CSS rule that explicitly sets the cursor for <ul> and <li> elements, like this:

ul, li {
    cursor: default;
}

To prevent the click event from firing for the children, you can check event.target, like this:

if (event.target !== this) return;
SLaks
thanks; it is also inherting the click event i mean i can click on the children also to toggle does it have the same explanation as well
sushil bharwani
can you please elaborate this line if (event.target !== this) return; i see it working but didnt get what exactly its doing
sushil bharwani
`e.target` is the element that fired the event. `this` is the element that you bound the handler to.
SLaks
+2  A: 

What you are seeing is event bubbling. When you click on a descendant element, the event also bubbles up to its ancestors. Your click handler on the ancestor element is what is being triggered. If you don't want this, you'll need to also stop event propagation in the click handlers of the child elements to prevent the event from bubbling up.

jQuery(li:has(ul)).children().find('li').click(function(e) {
    e.stopPropagation();
});
tvanfosson
seems like an interesting concept; just need a little more insight,even when there is no click event is defined on the child how is it bubbling up. Can you please suggest a resource where i can read more on it
sushil bharwani
@sushil - You are confusing the event with the event handler you are creating. The event happens, in this case when the user clicks the mouse, whether there is a handler to do something about it or not. What you are doing is creating a bit of code that will be executed when the event happens. You might start with http://www.quirksmode.org/js/introevents.html or w3schools.com: http://www.w3schools.com/jsref/dom_obj_event.asp is also a good reference.
tvanfosson
thanks a lot for this insight.
sushil bharwani
A: 

yea try

jQuery('ul',this).css("cursor","hand !important"); .// to tell it to apply the cursor to the ul elements with "this" i.e the original li element

RobertPitt