2
votes

I'n new to javaScript and jQuery. How is this possible to call the click event of parent element when you click its child? I have this structure in my code:

<ul id="pc5">
   <li><a href="#">book</a>
   </li>
</ul>

I want something like this:

$("a").click(ul.click);

Any help would be appreciated.

EDIT: in my ul click function I need ul id attribute. something like this:

 ul.click(function(e){alert(e.target.id);

so when link is clicked, event.target isn't ul element.

4
when a child element is clicked the parent's click event also will be fired because of event bubbling unless the event propagation is prevented by the childArun P Johny
You don't need to do this - the click event from the a element will bubble to the ul, unless you use return false; or event.stopPropagation on the a click handler.Rory McCrossan

4 Answers

5
votes

If your child element is located inside your parent element you could also just add this CSS property.

.child {
   pointer-events: none
}

This way the click directly triggers the parent's click event listener.

This feature's support is quite good.

2
votes

You dont need to trigger element click events when child elements are clicked, the click event bubbles up the dom tree if you dont stop propagation.

Here you can see it working: jsfiddle just click on the blue span, the click event will bubble up to the ul :)

Updated question

If you want the id of the ul, simply to:

$('ul li a').click(function() {
  var id = $(this).closest('ul').attr('id');
});

Which would be even easier like so:

$('ul').click(function() {
   var id = $(this).attr('id');
   alert(id);
});

Working fiddle

This should work if you click on an since it bubbles up

1
votes

You should read about event propagation in jQuery. In few words: when user clicks on a then event will be propagated up in DOM tree.

0
votes

I had html like this:

<a href="?chk=1">
    <input id="CHK_1" name="CHK[1]" type="checkbox">
    <span>CHK 1</span>
</a>

where checkbox was supposed to be checked/unchecked only from server side. For reason i don't know, 'click' was not bubbling from checkbox to link, so i used js code like this:

$(document).on('click', '[id^="CHK_"]', function (e){
    window.open($(this).parent().attr('href'), '_self');
    e.preventDefault();
});