Open a Popup on Click Using visibility property
In this approach we are using the visibility property in CSS to toggle the visibility of a popup dialog. When the āOpen Popupā button is clicked, the openPop() function is called. This function checks the current visibility state of the popup and toggles it between visible and hidden.
Syntax:
const elementClasses =
document.getElementById('elementClasses');
elementClasses.style.visibility =
(elementClasses.style.visibility === 'visible') ? 'hidden' : 'visible';
Example: The below example uses the visibility property to open a popup on click using JavaScript.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
#popupDialog {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 20px
rgba(0, 0, 0, 0.3);
z-index: 1000;
visibility: hidden;
}
h1 {
color: #4caf50;
margin-bottom: 20px;
}
p {
color: #333;
margin-bottom: 15px;
}
button {
padding: 10px 20px;
background-color: #4caf50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s
ease-in-out;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div id="popupContainer">
<h1>w3wiki</h1>
<h3>Using visibility Property</h3>
<button onclick="openPop()">
Open Popup
</button>
<div id="popupDialog">
<p>Welcome to w3wiki!</p>
<button onclick="openPop()">
Close
</button>
</div>
</div>
<script>
function openPop() {
const popDialog =
document.getElementById(
"popupDialog"
);
popDialog.style.visibility =
popDialog.style.visibility ===
"visible"
? "hidden"
: "visible";
}
</script>
</body>
</html>
Output:
How to Open a Popup on Click using JavaScript ?
Opening a Pop-up when the click action is performed is the user-interactive technique. We can use this functionality in messages, or forms to show some error or alert messages before the user moves to the next action.
Table of Content
- Using display property
- Using classList Property
- Using visibility property