Article Image

4 Ways to Create a Modal Popup Box with Html, CSS and Vanilla JavaScript

Knowing is not enough; We must apply. Willing is not enough; We must do.

– Bruce Lee

Table of Content

Introduction

When creating the design of a web page, one of the most important things to be into consideration is user interactivity. A good example of user interactivity is the Modal box.

A modal box mostly appears as a message box in the Browser based on an action performed by a user. The modal box comes in different forms and shapes which includes the Alert box, Flash notification box, Dialog box, Lightbox. Etc.

The unique feature of the modal box is the fact that it disables the main window in the browser but keeps it visible, with the modal window showing as a child window in front of the web page.

Some of the important cases for using a modal in an application include:

  • Showing warnings for a certain course of action that may be irreversible.
  • Flash notifications on a new piece of information.
  • Increase in user interaction and engagement.

Modals have their disadvantages too, in that:

  • They can interrupt a user workflow.
  • They immediately demand the attention of the user.
  • They disable the contents in the background, which could be frustrating in some cases.

Now let us get started with the creation of the modals.



Sample 1

The flow of the tutorial will see us create three files, the index.html, style.css and app.js files, over four samples. Then we give a detailed breakdown of the code in each of these files.

index.html

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/a71707a89a.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="./style.css"/>
<title>Popup Box</title>
</head>
<body>
<div id="popUpOverlay"></div>
<div id="popUpBox">
<div id="box">
<i class="fas fa-check-circle fa-5x"></i>
<h1>Here Goes Your Popup</h1>
<div id="closeModal"></div>
</div>
</div>
<button onclick="Alert.render('You look very pretty today.')" class="btn">Show Alert</button>
<script src="./app.js"></script>
</body>
</html>

 

In the index markup page above, we have a Font Awesome script within the head tag, which we will be using inside the modal box to display an icon. We also linked the CSS and javascript pages on the index page.

In the body of the index page, we have some important HTML attributes like the id’s which will be used later in our javascript file to manipulate the page.

Then lastly in our button tag, we have an onclick event attribute which has an Alert function that gives us the functionality to display the modal message on the page.

style.css

body{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.btn{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: pink;
  font-size: 20px;
  color: white;
  padding: 10px 30px;
  cursor: pointer;
}

#popUpBox{
  width: 500px;
  overflow: hidden;
  background: pink;
  box-shadow: 0 0 10px black;
  border-radius: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  padding: 10px;
  text-align: center;
  display: none;
}

In the style.css file, we set the box-sizing of our page to border-box. This property allows us to include the padding and border in an element’s total width and height.

Then we styled our button with the .btn class. This allows us to position the button that allows us to display the modal at the centre of the page.

Lastly, using the #popUpBox, we can position the modal at the centre of the page.

With the zindex property, we can stack the modal in front of the other elements in the page.

The most important thing to take note of in the style.css file is the fact that we set the initial state of the display property as none. The reason for this will be explained in the app.js file.

app.js

var Alert = new CustomAlert();

function CustomAlert(){
  this.render = function(){
      //Show Modal
      let popUpBox = document.getElementById('popUpBox');
      popUpBox.style.display = "block";
      //Close Modal
      document.getElementById('closeModal').innerHTML = '<button onclick="Alert.ok()">OK</button>';
  }
  
this.ok = function(){
  document.getElementById('popUpBox').style.display = "none";
  document.getElementById('popUpOverlay').style.display = "none";
}
}

Here, we have a global variable called Alert, which instantiates a function called CustomAlert(). Inside this function, we:

  • Accessed the #popUpBox (id). With this, we set the display as block which shows the modal when the button tag is clicked. Remember, the initial state was set as none in the CSS file.
  • Closed the modal by accessing the closeModal (id) in the HTML file. With this we able to set an HTML Button tag, with an onclick event attribute. In there we declared a function called ok().
  • Finally, referencing the ok() function, we set the CSS properties of the modal to none, when the button gets clicked.

With that, we should have the result below:

Gif showing a modal for example one

Sample 2

We start with the index.html, style.css and app.js files respectively.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://kit.fontawesome.com/a71707a89a.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="./style.css"/>
  <title>Popup Box</title>
</head>
<body>
    <input 
      type="button" 
      value="Test the alert" 
      onclick="alert('...but something went wrong');" 
      class="btn"
      />
<script src="./app.js"></script>
</body>
</html>

From the above, we have the relevant links to our CSS and JavaScript files. Then in the body of the index page, we have an input tag with the type of Button.

We also have an onclick event attribute, with an alert() method containing a text that will be displayed in the modal.

style.css

.btn{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgb(48, 48, 177);
  font-size: 20px;
  color: white;
  padding: 10px 30px;
  cursor: pointer;
}

#modalContainer {
    background-color:rgba(0, 0, 0, 0.3);
    position:absolute;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
    z-index:10000;
}

#alertBox {
    position:relative;
    width:500px;
    min-height:100px;
    margin-top:250px;
    border:1px solid #666;
    background-color: pink;
    background-repeat:no-repeat;
    background-position:20px 30px;
}

#alertBox h1 {
    margin:0;
    font:bold 0.9em verdana,arial;
    background-color:white;
    color: black;
    border-bottom:1px solid #000;
    padding:2px 0 2px 5px;
}

#alertBox p {
    font:0.7em verdana,arial;
    height:50px;
    padding-left:5px;
    margin-left:55px;
}

#alertBox #closeBtn {
    display:block;
    position:relative;
    margin:5px auto;
    padding:7px;
    border:0 none;
    width:70px;
    font:0.7em verdana,arial;
    text-transform:uppercase;
    text-align:center;
    color:#FFF;
    background-color:#95b9d8;
    border-radius: 3px;
    text-decoration:none;
}

 

Here we:

  • Styled our button with the .btn class that was declared in the index.html file
  • Then we have modalContainer, alertBox, alertBox h1, alertBox p, alertBox #closeBtn ID’s. All these are created in the app.js file. A different approach from how we created the modal in Sample 1

app.js

var titleAlert = "It Pops!!!";
var closeModal = "Ok";

if(document.getElementById) {
    window.alert = function(txt) {
        createCustomAlert(txt);
    }
}

//Function To Create Custom Alert
function createCustomAlert(txt) {
    doc = document;

    if(doc.getElementById("modalContainer")) return;

  //Create Div For Modal Container Body
    modalObject = doc.getElementsByTagName("body")[0].appendChild(doc.createElement("div"));
    modalObject.id = "modalContainer";
    modalObject.style.height = doc.documentElement.scrollHeight + "px";
  
   //Create Div For Alert Box Container Body
    alertObj = modalObject.appendChild(doc.createElement("div"));
    alertObj.id = "alertBox";
    if(doc.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
    alertObj.style.left = (doc.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
    alertObj.style.visiblity="visible";

   //Create Element For Title Alert
    h1 = alertObj.appendChild(doc.createElement("h1"));
  h1.appendChild(doc.createTextNode(titleAlert));
  
   //Create Tag For Alert Body Content
  	msg = alertObj.appendChild(doc.createElement("p"));
  	msg.appendChild(doc.createTextNode(txt));
  	msg.innerHTML = txt;

     //Create Tag To Close Modal Button
    btn = alertObj.appendChild(doc.createElement("a"));
    btn.id = "closeBtn";
    btn.appendChild(doc.createTextNode(closeModal));
    btn.href = "#";
    btn.focus();
    btn.onclick = function() { removeCustomAlert();return false; }

    alertObj.style.display = "block";
    
}

  //Function To Remove Custom Alert
function removeCustomAlert() {
    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

Here we break things down into 6 different parts:

  • First, we set two global variables called closeModal and titleAlert which both hold the text that will be displayed in the modal box.
  • We declared a createCustomAlert() function. This is where we create the body of our modal, displayed on the page.
  • Then we created a div inside the body tag, assigned the modalContainer ID to it and then set the height to the scroll height of the page
  • The div for the body of the alert box was created next. We assigned the alertBox ID to it. We then set the modal to be at the centre of the page, while also setting the style to be visible.
  • Next, we set the title of the modal box by creating an h1 tag. The titleAlert text variable is then appended to the h1 tag to show the “It Pops!!!” message. We did something similar to the body of the modal, by creating a tag and assigning a text node to it.
  • Lastly, we created a function called removeCustomAlert() to close the modal box. We do this by creating an tag, adding a closeBtn ID to it and creating an onclick event handler that references the function that closes the modal.

With that, we should have the result below:

Modal for Sample 2

Sample 3

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://kit.fontawesome.com/a71707a89a.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="style.css"/>
  <title>Pop Up</title>
</head>
<body>
  
  <a class="btn" onclick="pop()">Show Box</a>
  <div id="box">
    <i class="fas fa-check-circle"></i> 
    <h1>Good Job</h1>
    <a class="close" onclick="pop()">Close Box</a>
  </div>
<script src="app.js"></script>
</body>
</html>

In the index markup page above, we have a Font Awesome script within the head tag, which we will be using inside the modal box to display an icon. We also linked the CSS and javascript pages on the index page.

There is also two pop() functions declared in on the page, which we will be referring to in the app.js file.

style.css

.btn{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: pink;
  font-size: 20px;
  color: white;
  padding: 10px 30px;
  cursor: pointer;
}

#box{
  width: 500px;
  overflow: hidden;
  background: pink;
  box-shadow: 0 0 10px black;
  border-radius: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  padding: 10px;
  text-align: center;
  display: none;
}

#box span{
  color: hotpink;
  font-size: 40px;
  display: block;
  margin: 20px 0;
}

#box h1{
  color: brown
}

.close{
  font-size: 18px;
  color: white;
  padding: 10px 20px;
  cursor: pointer;
  background: rgb(111, 111, 223);
  display: inline-block;
  border-radius: 1px solid #000;
}

The styling above is straight forward. It is worthy to note that we set our #btn ID to a display of none, at the initial stage. We will be toggling the display property in the app.js file.

app.js

var modal = null
 function pop() {
   if(modal === null) {
     document.getElementById("box").style.display = "block";
     modal = true
   } else {
     document.getElementById("box").style.display = "none";
     modal = null
   }
 }

We start by setting a global variable called modal to null. Then we refer to the pop() function from the index.html page, afterwards, we set the conditional state of the modal.

If the modal is null at first and it gets clicked, we set the display to block and the modal variable to true to show the modal, and if the close button is clicked, we then set the display to none and the modal variable to null to remove the modal.

With this, we should have the result below:

modal for third sample

Sample 4

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css"/>
  <title>Pop Up</title>
</head>
<body>

  <button class="show btn">Click To See Modal </button>
  <div class="modal">
    <div class="modal-box">
        <span class="close-button">X</span>
        <h1>Hello, my name is modal</h1>
    </div>
</div>

<script src="app.js"></script>
</body>
</html>

 

Here we will be making use of CSS classes instead of ID’S to manipulate the state of our modal. We have a button tag to sho the modal and a span with the letter “X” to close the modal.

style.css

.btn{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: pink;
  font-size: 20px;
  color: white;
  padding: 10px 30px;
  cursor: pointer;
}


.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  opacity: 0;
  visibility: hidden;
}
.modal-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: pink;
  padding: 1rem 1.5rem;
  width: 24rem;
  border-radius: 0.5rem;
}
.close-button {
  float: right;
  width: 1.5rem;
  line-height: 1.5rem;
  text-align: center;
  cursor: pointer;
  border-radius: 0.25rem;
  background-color: lightgray;
}

.show-modal {
  opacity: 1;
  visibility: visible;
  transform: scale(1.0);
}

Here we styled our button and our modal. The .modal class has an initial state, whose visibility is hidden. We will toggle this with a javascript function to show the modal.

app.js

let modal = document.querySelector(".modal");
let show = document.querySelector(".show");
let closeButton = document.querySelector(".close-button");

function toggleModal() {
    modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
    if (event.target === modal) {
        toggleModal();
    }
}

show.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);

We are doing three things from the above:

  • We get access to our HTML classes through the querySelector. The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
  • Then we created a toggleModal() function that toggles the show-modal class in the CSS.
  • Then finally, we added event listeners to our functions to toggle the state of the modal based on a certain condition when the button is clicked.

With this, we should have the result below:

Modal sample 4



Conclusion

So there goes the implementation for our 4 Modals. You can style it however you want and implement it in any project you are working on. I know the design may not be the best, but the goal of the article was more focused on the javascript implementation rather than the design.

The link to the code can be found here on Github.

Subscribe for more tutorials here.

Leave a Comment

Your email address will not be published.