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";
}
});
2
Answers
Here you are:
Here, since you’re adding this event listener before the popup container is actually displayed, the popupContainer variable might not be accessible within the event listener’s scope at that moment.