Another method to achieve this is by utilizing a pre-existing modal box (div) that remains hidden until a specific button is clicked.
For instance, consider the following scenario where an overlay is included to appear behind the modal box. Upon clicking on the overlay while the modal box is visible, it will be hidden again.
$('#button').click(() => {
var display = $('#popup').css('display');
if (display === "none") {
$('#popup').show();
$('#overlay').fadeIn();
}
else {
$('#popup').hide();
$('#overlay').fadeOut();
}
});
$('#overlay').click(() => {
$('#popup').hide();
$('#overlay').fadeOut();
});
* {
margin: 0;
padding: 0;
}
#popup {
position: absolute;
background-color: #fff;
padding: 6%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 30%;
height: 30%;
border-radius: 30px;
z-index: 10;
display: none;
}
#overlay {
position: fixed;
background-color: rgba(0,0,0,0.5);
width: 100%;
height: 100%;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<div id="overlay"></div>
<div id="button">Click me</div>
<div id="popup">Text</div>
</body>
</html>