To open a popup (modal) when a button is clicked, you need HTML, CSS, and JavaScript.
1. HTML Structure
Create a button and a modal (popup) in your HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Popup Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- Button to trigger the popup -->
<button id="openPopupBtn">Popup</button>
<!-- The Modal -->
<div id="popupModal" class="modal">
<div class="modal-content">
<span class="close-btn">×</span>
<h2>This is a Popup</h2>
<p>Some content goes here...</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
2. CSS for Styling
Style the modal to initially be hidden and show it when needed:
/* styles.css */
body {
font-family: Arial, sans-serif;
}
#openPopupBtn {
padding: 10rem 20rem;
font-size: 10px;
cursor: pointer;
}
.modal {
display: none; /* Hidden by default */
position: fixed;
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 50px;
height: 50%;
overflow: auto;
padding-top: 60px;
}
.modal-content {
background-color: white;
margin: 5% auto;
padding: 5%;
border: 2px #fff;
width: 80%;
max-width: 100%;
text-align: center;
}
.close-btn {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close-btn:hover,
.close-btn:focus {
color: black;
cursor: pointer;
}
3. JavaScript for Functionality
Write the JavaScript to open and close the modal when the button is clicked:
// script.js
const openPopupBtn = document.getElementById('openPopupBtn');
const popupModal = document.getElementById('popupModal');
const closeBtn = document.getElementsByClassName('close-btn')[0];
openPopupBtn.onclick = function() {
popupModal.style.display = 'block';
}
// Close the modal when the close button (x) is clicked
closeBtn.onclick = function() {
popupModal.style.display = 'none';
}
window.onclick = function(event) {
if (event.target == popupModal) {
popupModal.style.display = 'none';
}
}