I have written HTML/Javascript to show a popup box on the HTML page when the user clicks on a link. The popup works and can be closed by clicking on the x button. I want to add some functionality to also close the popup when the user clicks anywhere outside of the popup box.
Code is as follows:
<a href="#" id="popupLink" onclick="showPopup('This is test popup message'); return false;">poup test link</a>
<div id="popupContainer" class="popup-container">
<div id="popupContent" class="popup-content">
<!-- Content for the popup -->
</div>
<button id="popupClose" class="close-button">×</button>
</div>
The javascript is as follows:
function showPopup(content) {
// Get the elements by their ID
var popupLink = document.getElementById("popupLink");
var popupContainer = document.getElementById("popupContainer");
var popupWindow = document.getElementById("popupContent");
var popupClose = document.getElementById("popupClose");
// Set the content for the popup
popupWindow.innerHTML = content;
// Show the pop-up window
popupContainer.style.display = "block";
// Hide the pop-up window when the close button is clicked
popupClose.addEventListener("click", function() {
popupContainer.style.display = "none";
});
}
I have tried adding a document level event listener. But it is not working. After I add this, the popup does not show at all.
document.addEventListener("click", function(event) {
// Check if the clicked element is not inside the popup and not the link that opens it
if (!popupContainer.contains(event.target) && event.target !== popupLink && popupContainer.style.display === "block") {
console.log("inside the if block")
popupContainer.style.display = "none";
}
});
Here you are:
function showPopup(content) {
var popupContainer = document.getElementById("popupContainer");
var popupWindow = document.getElementById("popupContent");
var popupClose = document.getElementById("popupClose");
popupWindow.innerHTML = content;
popupContainer.style.display = "block";
popupClose.addEventListener("click", function() {
popupContainer.style.display = "none";
});
document.addEventListener("click", closePopupOutside);
}
function closePopupOutside(event) {
var popupLink = document.getElementById("popupLink");
var popupContainer = document.getElementById("popupContainer");
var popupWindow = document.getElementById("popupContent");
if (!popupWindow.contains(event.target) && event.target !== popupLink) {
popupContainer.style.display = "none";
document.removeEventListener("click", closePopupOutside);
}
}
.popup-container {
display: none;
}
/* Your styles for the popup */
<a href="#" id="popupLink" onclick="showPopup('This is test popup message'); return false;">poup test link</a>
<div id="popupContainer" class="popup-container">
<div id="popupContent" class="popup-content">
<!-- Content for the popup -->
</div>
<button id="popupClose" class="close-button">×</button>
</div>