Reputation: 429
I have a container div, with a on click event handler, with nested divs being created dynamically within the containe rdivs that also have on click event handlers.
However, the container div's event handler is being triggered before the nested div even though the nested div's are the ones being clicked. Can someone tell me why this is so? Based on what I have read, the nested div's event should be triggered first and if i want to i can stop the event from propagating upwards
On the console log, i am seeing "within toggle expand" then "cross icon got clicked"
<div class="container-fluid toggle-expand" style="background-color: #FCF8EC; border-radius: 10px; box-shadow: 0 0 5px 1px #000000; -webkit-box-shadow: 0 0 5px 1px #000000; -moz-box-shadow: 0 0 5px 1px #000000;"> </div>
var removeImg = $('<img />', {
id: 'remove_img' + containerIndex + '-' + this.id,
src: 'https://www.freeiconspng.com/uploads/black-close-icon-3.png',
alt: 'Delete icon',
class: 'removeImg',
css: {
'position': 'absolute',
'right': '15px',
'top': '5px',
'width': '30px'
}
});
$(document).on('click', '.toggle-expand', function(event){
console.log("Within toggle expand");
});
$(document).on('click', '.removeImg', function(event){
console.log("Cross icon got clicked");
})
Upvotes: 0
Views: 307
Reputation: 3496
Can you post the complete code? There seems to be something else that is wrong, because as you can see here, the event order is correct when I use your example:
(I can delete this answer if you provide us with a complete example where the problem is reproducible)
$(document).on('click', '.toggle-expand', function(event) {
console.log("Within toggle expand");
});
$(document).on('click', '.removeImg', function(event) {
console.log("Cross icon got clicked");
})
var removeImg = $('<img />', {
id: 'remove_img',
src: 'https://www.freeiconspng.com/uploads/black-close-icon-3.png',
alt: 'Delete icon',
class: 'removeImg',
css: {
'position': 'absolute',
'right': '15px',
'top': '5px',
'width': '30px'
}
});
$('.toggle-expand').append(removeImg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid toggle-expand" style="height: 100px; background-color: #FCF8EC; border-radius: 10px; box-shadow: 0 0 5px 1px #000000; -webkit-box-shadow: 0 0 5px 1px #000000; -moz-box-shadow: 0 0 5px 1px #000000;"> </div>
Upvotes: 1
Reputation: 41
you can use bubbling and capturing features to handle this. However there's another way that is event.target
that you can use, but the best way is bubbling and capturing
Upvotes: 0