Cyber Design
,

Creating a Modal Popup with JavaScript, CSS, and HTML: A Step-by-Step Guide

Modal Popup
Modal popups provide an elegant solution for displaying additional content or interactions without navigating away from the current page. In this tutorial, we’ll delve into creating a modal popup using JavaScript, CSS, and HTML. Follow the steps below to master the art of modal popups.

1. HTML Structure:

Start by creating the HTML structure for your modal. Define a button or link that will trigger the modal, and set up the modal container. Here’s a basic example:  
				
					<!DOCTYPE html>
<html lang="en">
<head>
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>Your Web Page Title</title>
</head>
<body>

<button id="openModalBtn">Open Modal</button>

<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Your modal content goes here.</p>
  </div>
</div>

<script src="script.js" defer></script>
<script>"use strict";function wprRemoveCPCSS(){var preload_stylesheets=document.querySelectorAll('link[data-rocket-async="style"][rel="preload"]');if(preload_stylesheets&&0<preload_stylesheets.length)for(var stylesheet_index=0;stylesheet_index<preload_stylesheets.length;stylesheet_index++){var media=preload_stylesheets[stylesheet_index].getAttribute("media")||"all";if(window.matchMedia(media).matches)return void setTimeout(wprRemoveCPCSS,200)}var elem=document.getElementById("rocket-critical-css");elem&&"remove"in elem&&elem.remove()}window.addEventListener?window.addEventListener("load",wprRemoveCPCSS):window.attachEvent&&window.attachEvent("onload",wprRemoveCPCSS);</script><script>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),this.deviceMode.id="elementor-device-mode",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&e.top<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",RocketElementorAnimation.run);</script><noscript><link rel="stylesheet" href="https://cyberdesign.ro/wp-content/cache/min/1/da8efeaa9aaaaa63101330be733327b0.css" media="all" data-minify="1" /><link rel='stylesheet' id='elementor-post-14-css' href='https://cyberdesign.ro/wp-content/uploads/elementor/css/post-14.css?ver=1715244695' media='all' /><link rel='stylesheet' id='elementor-post-71-css' href='https://cyberdesign.ro/wp-content/uploads/elementor/css/post-71.css?ver=1715244695' media='all' /><link rel='stylesheet' id='elementor-post-78-css' href='https://cyberdesign.ro/wp-content/uploads/elementor/css/post-78.css?ver=1715244695' media='all' /><link rel='stylesheet' id='elementor-post-57-css' href='https://cyberdesign.ro/wp-content/uploads/elementor/css/post-57.css?ver=1715244697' media='all' /><link rel='stylesheet' id='google-fonts-1-css' href='https://fonts.googleapis.com/css?family=Red+Hat+Display%3A100%2C100italic%2C200%2C200italic%2C300%2C300italic%2C400%2C400italic%2C500%2C500italic%2C600%2C600italic%2C700%2C700italic%2C800%2C800italic%2C900%2C900italic%7CInter%3A100%2C100italic%2C200%2C200italic%2C300%2C300italic%2C400%2C400italic%2C500%2C500italic%2C600%2C600italic%2C700%2C700italic%2C800%2C800italic%2C900%2C900italic&#038;display=swap&#038;ver=6.5.3' media='all' /></noscript></body>
</html>

				
			

2. CSS Styling:

Style your modal using CSS to control its appearance. Customize the styles according to your project’s design:

				
					/* styles.css */

.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  padding: 20px;
}

.close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 20px;
  cursor: pointer;
}

				
			

3. JavaScript Interaction:

Add JavaScript functionality to handle the opening and closing of the modal:

				
					// script.js

const openModalBtn = document.getElementById('openModalBtn');
const modal = document.getElementById('myModal');
const closeBtn = document.querySelector('.close');

openModalBtn.addEventListener('click', () => {
  modal.style.display = 'block';
});

closeBtn.addEventListener('click', () => {
  modal.style.display = 'none';
});

// Close modal if clicked outside the content
window.addEventListener('click', (event) => {
  if (event.target === modal) {
    modal.style.display = 'none';
  }
});

				
			

Now, you have a basic modal popup that opens when the button is clicked and closes when the close button or the outside area is clicked.

4. Customize and Integrate:

Customize the modal content and styles according to your project’s requirements. Integrate the modal into your web pages by copying the HTML structure and linking the CSS and JavaScript files.

Congratulations! You’ve successfully created a modal popup using JavaScript, CSS, and HTML. Enhance and tailor this example to suit your specific needs for a seamless integration into your web projects.

Facebook
Pinterest
Twitter
LinkedIn
Open chat
1
Scan the code
Hello 👋

Welcome to CyberDesign. How can we assist you today?