I have a main container with a wrapper inside it. Inside the wrapper I have a button that on click it appends a p element and hide the button. Now on click of the main container I want to hide the main container but on click of the elements inside the wrapper i didn't wanna hide the main container so I used stop propagation to solve this. Now the problem I have is once on click of the button I am appending a p element and it works but when I click on the p element the function assigned to it is not triggering because it was dynamically added and stop propagation is restricting it from firing. How can I solve this so that when the dynamically appended p element is clicked the function assigned to it fires. Thanks in advance.
$('.mainCon').on('click', function() {
$(this).css('display', 'none')
})
$('.wrapper button').on('click', function() {
$(this).css('display', 'none')
$('.wrapper').append('<p>Click me now</p>')
})
//not working
$('.wrapper p').on('click', function() {
console.log('clicked')
})
//not working
$('.mainCon .wrapper').click(function(e) {
e.stopPropagation();
});
//also not working
/*$('body').on('click', '.mainCon > *', function(e){
e.stopPropagation();
});*/
.mainCon {
display: flex;
width: 100%;
height: 200px;
background-color: gold;
}
.wrapper {
display: flex;
width: 70%;
height: 70%;
margin: auto;
background-color: pink;
}
.wrapper button {
height: 30%;
margin: auto;
}
.wrapper p {
text-decoration: underline;
cursor: pointer;
margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div >
<button>Click me 1st</button>
</div>
</div>
CodePudding user response:
One method to have a click event happen when you only click that element, and not the children element is to check where the event target is taking place. The following code will only do the action when you click on the .mainCon
and not anywhere else in the DOM.
$(document).on('click', (e) => {
const $container = $('.mainCon');
if($container.has(e.target).length === 0 && $container.is(e.target)) {
alert('Hello World!')
}
});
For the second issue with the .wrapper p
, the function is running before the p
element is ever created. So when you eventually create that p
, it is never getting the event listener added to it. To fix this issue, you can place the on click function after the append.
$('.wrapper button').on('click', function() {
$(this).css('display', 'none');
$('.wrapper').append('<p>Click me now</p>');
$('.wrapper p').on('click', function() {
alert('The P has been clicked!')
})
})