I have a simple popup when you click a button. If you click the x (#close
) it will close the popup. The goal is for it to also close if you click anywhere outside the popup. I have it so that if you click anything that doesn't have the class popup-content
, it should close the popup. For some reason, this is not working. If I change it so it closes if you click anything that DOES have the class popup-content
, then it closes when you click inside the popup.
What am I doing wrong here?
Also, is there a better way to do this that doesn't involve putting that class on every clickable part of the popup and button?
https://codepen.io/sharpdesigner/pen/wRMeeW
html
$(document).ready(function() {
$('#trigger').click(function() {
$('#overlay').fadeIn(300);
});
$('#close').click(function() {
$('#overlay').fadeOut(300);
});
});
$(document).mouseup(function(e) {
$("body").click(function(e) {
if (e.target.className !== "popup-content") {
$('#overlay').fadeOut(300);
}
});
});
.pop {
background: #000;
color: #fff;
text-align: center;
font-weight: bold;
padding: 10px 30px;
border-radius: 3px;
border: 1px solid #000;
display: inline-block;
cursor: pointer;
}
#overlay {
position: fixed;
height: 100%;
width: 100%;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.8);
display: none;
}
#popup {
max-width: 600px;
width: 80%;
max-height: 300px;
height: 80%;
padding: 20px;
position: relative;
background: #fff;
margin: 20px auto;
}
#close {
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="trigger" class="pop popup-content">Click me</a>
<div id="overlay">
<div id="popup" class="popup-content">
<div id="close">X</div>
<h2 class="popup-content">This is a popup</h2>
<p class="popup-content">You just triggered a popup</p>
</div>
</div>