I have a pop up that opens up so users can reply to messages. now when a user clicks <a>
tag it opens the popup, but it doesn’t close if they hit anywhere in the body. I tried fixing this by using jquery but it keeps opening and then closing the pop up again immediately after clicking on the <a>
tag.
My <a>
tag:
<a class="msg-icon2" onclick="openReplyModal(<?php echo $msg_id ; ?>)">
<i class="fas fa-reply"></i>
</a>
My jquery:
var msg_id;
function openReplyModal(id) {
msg_id = id
$("#reply_modal" + msg_id).fadeIn();
jQuery(document).ready(function($) {
jQuery("body").click(function() {
$("#reply_modal" + msg_id).fadeOut();
});
});
}
How can I adjust my code so that when the user clicks the button for the first time it would open the popup and stay opened unless he clicks anywhere in the body
?
here is the code i got from the answer below:
`function openReplyModal(id, event) {
$(".modal").hide(); // close other modal
msg_id = id
$("#reply_modal" + msg_id).fadeIn();
event.preventDefault();
event.stopPropagation();
}
jQuery(document).ready(function($) {
// click on modal doesn't hide itself
$("body").on("click", ".modal", function(e) {
e.stopPropagation();
});
// clicl anywhere else hides all modals
$(window).click(function() {
$(".modal").fadeOut();
});
});`
2
Answers
Give all your modals a common class, such as
class="reply_modal"
. Then you can have a general click handler that fades them all out when you click on the body.The reason that the modal closes immediately is that the
click
event bubbles out from the<a>
to the body, so it closes the modal. I addedevent.stopPropagation()
to the function so it won’t bubble out.Use
$(window).click()
to detect clicks anywhere in the window outside the element. See How do I detect a click outside an element?.