I am creating a pop-up for my products when an icon is clicked. I want to make it so that the pop-up automatically disappears once the user clicks somewhere outside of the pop-up box. Currently, the only way for the pop-up to close and disappear is to click the same icon button that makes the pop-up appear to begin with. Id appreciate it if you could help me by using the code I provided as I am a beginner and will probably not be able to incorporate general suggestions but I will of course try my best! Thank you guys so much for the help and suggestions in advance.
HTML Pop up Code
<div class="box">
<div class="icons">
<a href="#contact" class="fas fa-shopping-cart"></a>
<div class="popup" onclick="myFunction()">
<span class="popuptext" id="myPopup">RAW Pipe Cleaners are naturally strong and absorbent and wrapped around a flexible banded iron core. These are the natural way to clean your pipe or rig! A RAW Innovation!</span>
<a href="#" class="fas fa-info">
</a></div>
<a href="#" class="fas fa-eye"></a>
</div>
Pop Up CSS Code
/* Popup container */
.popup {
position: relative;
display: inline-block;
cursor: pointer;
}
/* The actual popup (appears on top) */
.popup .popuptext {
visibility: hidden;
width: 300px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 8px 0;
position: absolute;
z-index: 1;
bottom: -740%;
left: 50%;
margin-left: -150px;
height: 400px;
font-size: 18px;
padding: 50%;
}
/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}
@keyframes fadeIn {
from {opacity: 0;}
to {opacity:1 ;}
}
Pop up JS Code
// When the user clicks on <div>, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
You can create a new variable and state that when the user clicks outside of the popup area it auto-closes.
window.onclick = function(event) {
if (event.target == popup) {
popup.style.display = "none";
}
}