Howdy Folks, welcome to this new tutorial. In this tutorial, you will learn how to create a simple modal popup window/dialog box by only using HTML, CSS, and vanilla Javascript from scratch. Modal Popups are used pretty frequently on the web. They are cool to use too. Here we will be making a simple version of the modal popup box. Here's how they look like once finished:

first screenThat's our initial screen. When you hit that button, the modal popup will popup like below:

modal screen

You can also see the live demo here --> https://codepen.io/thecodingpie/pen/XWXaYqy. And you can get the final code on Github --> https://github.com/the-coding-pie/Modal-Popup-Box.

Prerequisites

I assume that you had a decent understanding of HTML, CSS, and a little bit of Javascript. And you should be aware of how flexbox in CSS works. Because we will be using a little bit of flexbox in this tutorial. 

I am going to use visual studio code as my text editor. You are free to use whatever code editor you like. And finally, make sure you have installed "Live Server" by Ritwick Dey in visual studio code. If you don't have Live Server installed, then:

  • Open visual studio code
  • Go to Extensions tab (Ctrl + Shift + X)
  • Search for "Live Server" by Ritwick Dey
  • Then Install it

Now let's get started :)

Initial Setups

This is my file structure:

folder structure

  • First, create the root folder that holds everything and name it as "Modal Popup Box".
  • Then open this folder in visual studio code.
  • Then directly inside that root folder, create a file named "index.html" --> This holds our HTML.
  • Then again directly inside our root folder, create two folders:
    • One named "css" --> Inside this folder, create a file named "styles.css".
    • Then another folder named "js" --> Inside this folder, create a file named "script.js".

That's it. Now you should have a folder structure similar to above. From here on I will be doing everything bit by bit so that you can get a better understanding of what we are doing... Now the HTML part...

HTML

Open the "index.html" file and type the following:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="css/styles.css">
  <title>Modal Popup Box</title>
</head>
<body>

  <script type="text/javascript" src="js/script.js"></script>
</body>
</html>

That's our boilerplate code. There's nothing special in there. We are giving some <meta> tags, one for setting the charset, and one for the viewport. They are not required here. But always using them is a good practice. Then we are linking our "styles.css" file. Then set the title. Before the ending </body> tag, we are linking our "script.js" file. That's it.

Now type the following code between <body> and opening <script> tag.

<!-- Modal Open Button -->
  <button id="open-btn">
    OPEN THE MODAL
  </button>

The above code is for the "OPEN THE MODAL" button. I am also giving it an id="open-btn" so that we can easily grab it inside javascript.

Now come the actual modal background and the modal itself. Copy the following code below the above code:

<!-- Modal Background and Modal -->
  <div id="modal-background">
    <div id="modal">
      <span id="close-btn">&times;</span>
      <p>HOWDY FOLKS!</p>
      <div class="buttons">
        <button class="yes">
          YES
        </button>
        <button class="no">
          NO
        </button>
      </div>
    </div>
  </div>

If you take a look at the finished version (or the image at the top), you can see a light grey background when the modal pops up. That why the first <div id="modal-background"> is for. It spreads a grey background on the entire screen. Then the <div id="modal"> is the actual modal. Inside our modal, we have a close-btn. I am not using the alphabet "X" for the cross mark. Rather I am using HTML special character "&times;", which gives you the desired symbol. Then we had a <p> which says "HOWDY FOLKS!". Then to give a little beauty to our modal, I am giving two dummy "yes", "no" <button> with a class of the same name, and wrapping them inside <div class="buttons">.

The final code for "index.html" looks like below:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="css/styles.css">
  <title>Modal Popup Box</title>
</head>
<body>
  
  <!-- Modal Open Button -->
  <button id="open-btn">
    OPEN THE MODAL
  </button>

  <!-- Modal Background and Modal -->
  <div id="modal-background">
    <div id="modal">
      <span id="close-btn">&times;</span>
      <p>HOWDY FOLKS!</p>
      <div class="buttons">
        <button class="yes">
          YES
        </button>
        <button class="no">
          NO
        </button>
      </div>
    </div>
  </div>

  <script type="text/javascript" src="js/script.js"></script>
</body>
</html>

Open it with Live Server by right-clicking on the "index.html" file (inside visual studio code), then scroll down and click on the "Open with Live Server" option and take a look at it at the browser. You can't see any styling now. Because we only linked the "styles.css" file but didn't write any CSS styles. So now let's do that. Let's add some styles...

CSS

Open the "styles.css" file you created and type the following:

/* common styles */
body {
  font-family: sans-serif;
}

button:hover {
  cursor: pointer;
}

/* common styles end */

They are some common styles. The first style is to set our font inside the entire body. The second style gets activated when we :hover over any button inside our page. When we hover our cursor over any button, we need to change the icon of the cursor to pointer (like the hand symbol). 

Now below that type the following:

/* modal part */
#modal-background {
  background-color: rgba(0, 0, 0, 0.2);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

If you take a look at the browser, you can see a grey background. The above style is for that. We are selecting the <div id="modal-background"> by using the "#" symbol. We use # to select id. Like that, to select class, we use "." (dot). After selecting the div, we give it a background-color of black with an alpha of 0.2. The first three zeros, inside rgba() represents the black color (the hex code for black is 000). Then the last 0.2 is for alpha. Then we are setting position: fixed from top: 0 and left: 0, so that it will not scroll with the rest of the page. Then set width: 100% and height: 100% and give z-index: 1. You can google what z-index is.

Now the style for the actual modal. Type this below the above code:

#modal {
  background-color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  padding: 10px 20px;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
  font-size: 1.5rem;
}

Here we are selecting the <div id="modal"> which represents the actual modal and give it a background-color of white(#fff). Then we need to position it absolutely center, ie, push it from top: 50% and left: 50% and transform: translate(-50%, -50%). Now it will be centered. Then give a width: 200px and apply some padding: 10px 20px. This is a shorthand for applying padding 10px to top and bottom and 20px for left and right. Then give a border-radius: 5px for a curved edge. Then display: flex and flex-direction: column is for aligning everything vertically, ie one below another. Then align-items: center is for centering everything horizontally. Then apply some box-shadow. And set the font-size: 1.5rem. Now style the dummy buttons by adding the code below:

.yes, .no {
  border: none;
  padding: 7px 14px;
  font-size: 1rem;
  border-radius: 5px;
}

.yes {
  background-color: #00ff00;
}

.no {
  background-color: #ff0000;
}

The above styling is for the dummy .yes .no buttons. That is pretty self-explanatory and less important too. So let's keep moving... Type the code below:

#close-btn {
  align-self: flex-end;
}

#close-btn:hover {
  cursor: pointer;
  color: #ff0000;
}

/* modal part end */

They are for the <span id="close-btn">. The first style above pushes the close-btn to the right side. The second style changes the cursor: pointer and color of the button to red(#ff0000) when hovering.

Now the modal is always showing up, so we need to hide it. To do that, add display: none to the #modal-background.

display: none; 

Then we need some animation while the modal pop up. This is not necessary, but it will be cool to see. For that copy the code below and paste it inside #modal


  animation-name: animatemodal;
  animation-duration: 0.4s;

And paste this code at the very bottom of the "styles.css" file:

/* animation part */
@keyframes animatemodal {
  from {
    top: -300px;
    opacity: 0;
  }
  to {
    top: 50%;
    opacity: 1;
  }
}
/* animation part end */

All our CSS part is done. If you want a little bit of explanation of the above code, then watch this short video by The Net Ninja --> https://www.youtube.com/watch?v=PjR97QzOrJM

This is the final code for "styles.css". Make sure the code you typed up to this point is exactly like the below:

/* common styles */
body {
  font-family: sans-serif;
}

button:hover {
  cursor: pointer;
}

/* common styles end */

/* modal part */
#modal-background {
  display: none;
  background-color: rgba(0, 0, 0, 0.2);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

#modal {
  background-color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  padding: 10px 20px;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
  font-size: 1.5rem;
  animation-name: animatemodal;
  animation-duration: 0.4s;
}

.yes, .no {
  border: none;
  padding: 7px 14px;
  font-size: 1rem;
  border-radius: 5px;
}

.yes {
  background-color: #00ff00;
}

.no {
  background-color: #ff0000;
}

#close-btn {
  align-self: flex-end;
}

#close-btn:hover {
  cursor: pointer;
  color: #ff0000;
}

/* modal part end */

/* animation part */
@keyframes animatemodal {
  from {
    top: -300px;
    opacity: 0;
  }
  to {
    top: 50%;
    opacity: 1;
  }
}
/* animation part end */

Now let's add the functionalities using a little bit of javascript...

Javascript

Again I assume that you already had a basic understanding of javascript. If not, don't worry just move forward. I will try my best to explain everything in simple words ;)

We need to make our modal working right? But how we are going to do that? The idea is quite simple.

  • When the user clicks on the "OPEN THE MODAL" button, we need to make the "modal" and "modal-background" visible or popup.
  • Then, when the user clicks on the "close-btn" on the modal, we need to hide/close the "modal" and the "modal-background".
  • Also, if the user clicks somewhere outside the modal when it is visible, we need to hide/close the "modal" and the "modal-background".

They are the basic functionalities we need to do. 

To do that inside the "script.js" file, we need a reference to all the necessary components like "OPEN THE MODAL" <button> and "close-btn" inside "script.js" file, right? That's what we are going to do now:

Open the "script.js" file and type the following:

// select the open-btn button
let openBtn = document.getElementById('open-btn');
// select the modal-background
let modalBackground = document.getElementById('modal-background');
// select the close-btn 
let closeBtn = document.getElementById('close-btn');

Above we are just grabbing the <button id="open-btn">, ie the "OPEN THE MODAL" <button>, <div id="modal-background"> and <span id="close-btn"> and saving them inside the variables openBtn, modalBackground and closeBtn. let is a keyword in javascript that tells the compiler that whatever comes after it is a variable.

Now we had the reference to the elements. Let's add the functionality:

// shows the modal when the user clicks open-btn
openBtn.addEventListener('click', function() {
  modalBackground.style.display = 'block';
});

The above code adds an eventListener of type 'click' to the openBtn. It basically means this, whenever someone clicks on the openBtn, it listens to that event. When that click event happens, the function() {} inside it will get executed.

We attach an eventListener to an element through addEventListener().

Here we are just changing the style of <div id="modal-background"> from display:none to display:block. It will make the modalBackground visible. 

Now take a look at the browser. If you click on the "OPEN THE MODAL" button, the modal will pop up :)

But it is not closing right. Let's add it.

We had already selected the close-btn and stored it inside the closeBtn variable. Now add an eventListener to that button exactly like above.

// hides the modal when the user clicks close-btn
closeBtn.addEventListener('click', function() {
  modalBackground.style.display = 'none';
});

Here when the user clicks on the close-btn, we need to hide the modal right? That is done by changing the style of modalBackground from display:block to display:none. That's what we are doing above.

Also when the user clicks on somewhere outside the modal when it is visible, we need to do the same thing. So type the following at the bottom of the file:

// hides the modal when the user clicks outside the modal
window.addEventListener('click', function(event) {
  // check if the event happened on the modal-background
  if (event.target === modalBackground) {
    // hides the modal
    modalBackground.style.display = 'none';
  }
});

Here when the event happens on the browser window, we need to check that if the event happened on the modal-background or not. If it happened on modal-background, then we need to hide the modal. That's what we are doing above with the if statement.

Hooray, we had done it :) Now our modal will function as we expected. The yes, no buttons are dummy buttons. So they won't work. But you can make it work by the skills you now acquired. 

The final code for "script.js":

// select the open-btn button
let openBtn = document.getElementById('open-btn');
// select the modal-background
let modalBackground = document.getElementById('modal-background');
// select the close-btn 
let closeBtn = document.getElementById('close-btn');

// shows the modal when the user clicks open-btn
openBtn.addEventListener('click', function() {
  modalBackground.style.display = 'block';
});

// hides the modal when the user clicks close-btn
closeBtn.addEventListener('click', function() {
  modalBackground.style.display = 'none';
});

// hides the modal when the user clicks outside the modal
window.addEventListener('click', function(event) {
  // check if the event happened on the modal-background
  if (event.target === modalBackground) {
    // hides the modal
    modalBackground.style.display = 'none';
  }
});

We do the popup working by just changing the style from display: none to display: block and vice-versa. I hope you understood that.

Conclusion

I hope you enjoyed this tutorial. If you had any doubts, then please comment them below. Thank you ;)