Step 1: Create the HTML Structure
First, set up the basic structure of the modal in your HTML file
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Custom Modal Popup</title> <link rel="stylesheet" href="styles.css"> </head> <body> <!-- Button to Open Modal --> <button id="openModal">Open Modal</button> <!-- Modal Structure --> <div id="customModal" class="modal"> <div class="modal-content"> <span class="close">×</span> <h2>Custom Modal</h2> <p>This is a simple modal popup created using Vanilla JavaScript.</p> </div> </div> <script src="script.js"></script> </body> </html>
STEP 2: Style the modal with CSS
Now add some CSS to Style the modal and make it look appealing.
/* styles.css */ /* Hide modal by default */ .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent background */ } /* Modal Content */ .modal-content { background: white; margin: 15% auto; padding: 20px; border-radius: 10px; width: 40%; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); position: relative; text-align: center; } /* Close button */ .close { position: absolute; top: 10px; right: 20px; font-size: 24px; cursor: pointer; }
STEP 3: Add Javascript to Handle Modal Functionality
Now write javascript to open and close the modal.
// script.js // Select elements const modal = document.getElementById("customModal"); const openBtn = document.getElementById("openModal"); const closeBtn = document.querySelector(".close"); // Function to open the modal openBtn.addEventListener("click", () => { modal.style.display = "block"; }); // Function to close the modal when the close button is clicked closeBtn.addEventListener("click", () => { modal.style.display = "none"; }); // Close modal if user clicks outside of modal content window.addEventListener("click", (event) => { if (event.target === modal) { modal.style.display = "none"; } });