<div id="addCompaniesModal">
<div id="addCompany_map"></div>
<div class="addMarkerBtn"></div>
</div>
Hi there when i click on the child addCompany_map the parent addCompaniesModal should not be called ... I have done something like this.. but for some reason it didnt work..and parent div is getting selected on clicking on child can some one please explain me the solution
$(document).on('click','#addCompany_map', function (e) {
e.stopPropagation();
});
$('#addCompaniesModal').click(function(){
});
Event propagation is happening from the child elements to parent elements.
It may look like your first line is handling the click on the child div but the way you specified it actually handles the click on the document level (because your selector is $(document)
) and it only calls the method if it happened on the child div (the on('click','#addCompany_map'
part). Since the document is parent to addCompaniesModal
div, it's click handler will fire after the one used on addCompaniesModal
div.
In order for this to work, you'll need to change the code to this:
$('#addCompany_map').click(function (e) {
e.stopPropagation();
});
$('#addCompaniesModal').click(function(){
});
EDIT:
I've seen in some of your comments that the main reason you're using $(document).on('click', ...
approach is because you're adding child divs dynamically.
In that case, there are 2 viable approaches to handling your problem.
First approach is for you to also dynamically add child div handler, and unbind upon removal. You could use this approach:
function dynamicallyAddChildren(){
var oldChildDiv = $('#addCompany_map');
if (oldChildDiv.length > 0)
oldChildDiv.off('click', handleChildDiv);
// remove old child if needed and add new child divs
newChildDiv.on('click', handleChildDiv);
}
function handleChildDiv(e){
//do something
e.stopPropagation();
}
$('#addCompaniesModal').click(function(){
});
Second approach is to use $(document).on('click', ...
approach with both child and parent divs like this:
$(document).on('click','#addCompany_map', function (e) {
e.stopPropagation();
});
$(document).on('click','#addCompaniesModal', function(){
});
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