We’ll create a button which shows a pop-up and pop-out window when you click on the button. For this we’ll use a JavaScript function which will be linked to the HTML using onClick keyword on the HTML linked to the button. Here’s the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="popup" id="popup-window">
<div class="overlay"></div>
<div class="content">
<div class="close-btn" onclick="popupWindow()">×</div>
<h1>A Sample PopUp Window</h1>
<p>
This is a simple sample pop up window for an absolute beginner. This
has been created using front-end technologies like HTML, CSS and
JavaScript. To close the window click on the cross icon.
</p>
</div>
</div>
<button onclick="popupWindow()">Click Here</button>
<script src="index.js"></script>
</body>
</html>
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
}
button {
color: #fff;
background-color: rgb(24, 24, 24);
padding: 20px;
border: none;
border-radius: 20px;
font-size: 25px;
cursor: pointer;
}
button:hover {
background-color: rgb(67, 66, 65);
}
.popup .overlay {
position: fixed;
top: 0px;
left: 0px;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.7);
z-index: 1;
display: none;
}
.popup .content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
background: #fff;
width: 450px;
height: 250px;
z-index: 2;
text-align: center;
padding: 40px;
box-sizing: border-box;
}
.popup .close-btn {
position: absolute;
right: 20px;
top: 20px;
width: 30px;
height: 30px;
background: #222;
color: #fff;
font-size: 25px;
font-weight: 600;
line-height: 30px;
text-align: center;
border-radius: 50%;
cursor: pointer;
}
.popup.active .overlay {
display: block;
}
.popup.active .content {
transition: all 300ms ease-in-out;
transform: translate(-50%, -50%) scale(1);
}
Next, the code block below, note that the popupWindow() function which has been written in JS has been linked in the HTML using onClick keyword inside the button element.
function popupWindow() {
document.getElementById("popup-window").classList.toggle("active");
}