user1489970 user1489970 - 1 year ago 79
Javascript Question

Nested Click Event bubbling issue

I am working with a nested click event (there is a large array of images, some with children images, some without).

Onclick for all of the images (children, parent and non-parent), they should display in a diff css div, and then remove themselves if clicked again, indefinitely.

So far this code works for the parent and non-parent images, but bubbling is making the children images display the parent images instead.

If I return false to stop the bubbling before the children function, it will break the functionality for the parent and non-parent images that are further down in the array (the children are in a new popup css, not a list), but if I don't stop the bubbling, the nested click event won't run.

Anyone see a good way around this mess?

// Click an image, and it will change it in the demo css class panel
$('.item-button').click(function(event) {
var layerID = $(this).attr('data-layer'); //these do not correspond to actual layers of nesting.
var itemID = $(this).attr('data-item');
var itemmulti = $(this).attr('data-multi'); //this value def works to recognize parent from other non-parent items (not children).
var clayerID = $(this).attr('data-clayer');
var citemID = $(this).attr('data-citem'); //child item 1.

if(( $(this).data('status') == 'clicked') || itemID == 0) {
var imageSrc = $(this).parent().find('img').attr('id');
$(layerID).attr('src', imageSrc);
} else {
var imageSrc = $(this).parent().find('img').attr('id');
$(layerID).attr('src', imageSrc);

if (itemmulti != 0) {
//begin headache.
document.getElementById('child-' + itemID).style.display = "inline-block";

//this is where a separate click function for children items begins.
$('.item-sub1').click(function(event) {

if(( $(this).data('status') == 'click') || citemID == 0) {
var imageSrc = $(this).parent().find('img').attr('id');
$(selector).attr('src', imageSrc);
} else {
var imageSrc = $(this).parent().find('img').attr('id');
$(clayerID).attr('src', imageSrc);
return false;

<img button title id alt />
<input radio id="layer-{ID}-{item.ID}-radio" name="layer-{ID}" value="{item.ID}" class="item-button" data-multi="{item.PARENT}" data-layer="{ID}" data-item="{item.ID}" />
<!-- IF item.CHILD1 != 0 -->
<div id="child-{item.ID}" style="width: 300px; position: absolute; display: none;">
<img button here title data-layer="{item.CLAYER1}" data-item="{item.CHILD1}">
<input radio id="layer-{item.CLAYER1}-{item.CHILD1}-radio" name="layer-{item.CLAYER1}" value="{item.CHILD1}" style="display: none;" class="item-sub1" data-clayer="{item.CLAYER1}" data-citem="{item.CHILD1}" />

Answer Source

I think what you need to do to prevent the event from bubbling up the DOM tree and preventing any parent handlers from being notified of the event is to use stopPropagation() method.

$('.item-button').click(function(event) {
     // your code...

For more info: 1. jquery 2. javascript