I need to create a modal for html page. When a button on the page is clicked, the modals shows up. Button to close modal contains in the modal itself.
The problem is that click event on close button, that meant to remove a modal html from document, is not working. However, console.log
assigned to the same event show up in console. Why is that happening and how to fix it?
Pen: https://codepen.io/t411tocreate/pen/prZRYN
Js code:
$(document).ready(function(){
$('#showModal').on('click', function() {
$('.container').append(modalHtml)
})
$(document).on('click','#closeModal',function(){
console.log('click triggered')
$(document).remove('#modal')
})
var modalHtml = '<div id="modal"> <div class="modal-bg"></div><div class="modal-content"> <p>this is a modal</p><span id="closeModal">close</span> </div></div>'
})
Call remove()
directly on the element - use $('#modal').remove()
instead - see demo below:
$(document).ready(function() {
$('#showModal').on('click', function() {
$('.container').append(modalHtml)
})
$(document).on('click', '#closeModal', function() {
$('#modal').remove();
})
var modalHtml = '<div id="modal"> <div class="modal-bg"></div><div class="modal-content"> <p>this is a modal</p><span id="closeModal">close</span> </div></div>'
})
#showModal {
margin: 50px 40%;
font-size: 50px;
}
#modal {
display: block;
}
#modal .modal-bg {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
#modal .modal-bg:before {
content: "";
display: block;
height: 100%;
position: absolute;
top: 0;
left: 0;
width: 100%;
background-color: rgba(43, 43, 43, 0.5);
}
#modal .modal-content {
width: 50%;
margin: 20px auto;
position: relative;
background: black;
color: #fff;
padding: 20px;
}
#modal .modal-content #closeModal {
padding: 10px;
margin: 10px;
border: 1px solid #fff;
}
#modal .modal-content #closeModal:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button id="showModal"> Show modal</button>
</div>