Making a Modal – Vanilla JavaScript ES5 (Part1)

What will we be doing?

We will be doing a modal that appears when the user clicks a button. We will display an overlay with the ability to close the modal when clicking the overlay, as well as have an ‘X’ on the modal it’self, that would close the button.

As usual, there are many ways to do the modal, but in this tutorial, I’ll explain how you can make that little awesome modal.

You can check the code on CodePen here: https://codepen.io/lovetocodex/pen/mpxmjY?editors=1010

Now that you know what you’ll be doing, and you’re excited to make it, let’s jump into it straight away!

 

What are modals used for?

A modal is an awesome way to give provide fast, focused, contextual interaction. If a user is doing something perhaps and he wants to sign in, a modal can be good. From any page he can click the ‘sign in’ button, complete the form and get back to his current task.

Unlike if the user was doing something, and a modal just pops up in his face, that’s an unwanted interruption that the user will not like, and might get distracted resulting in living your page – okay, that was an extreme one, but it all depends. Modals can be very good for marketing. A buddy of mine get’s most of his subscribers through his modal – however on some sites, the modal might not be appropriate.

The HTML

<div class="vert-mid">
<button class="modal-btn"> Click Me </button>
</div>

<div class="modal">

    <div class="modal__inner">
        
        <div class="modal__header">
        <h1>Awesome Modal</h1>
        <button class="modal__close">
                 &#x2716;
        </button>
        
        </div>
        
        <div class="modal__content">
            <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Voluptas corporis, ad quae sit reprehenderit amet, ipsam delectus error excepturi suscipit labore. Neque animi vero perspiciatis accusamus doloribus praesentium minus magnam.</p>
        </div>

    </div><!-- /modal__content -->
    
</div>

 

The CSS

Note that the modal-overlay is fixed an index of 5, while the modal it’self-has an index of 10. That is because we want the modal overlay to be behind the actual modal – otherwise, we wouldn’t be able to select what’s in the modal or see the modal at all.

We gave the overlay position fixed because we want it to be displayed in front of anything and be there even when the user scrolls down – ultimately we can disable to scrolling when the modal is on.

Here’s the CSS:

body {
    background-color: orange
}

.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;

    width: 100%;
    height: 100%;

    -webkit-transition: .15s ease-in-out;
       -moz-transition: .15s ease-in-out;
        -ms-transition: .15s ease-in-out;
         -o-transition: .15s ease-in-out;
            transition: .15s ease-in-out;

  background: rgba(0,0,0,.6);
    visibility: hidden;
    transition: .20s ease-in-out;
    opacity: 0;
    z-index: 5;
}

.modal-overlay.is-open {
    visibility: visible;
    opacity: 1;
}

.modal {
  visibility: hidden;
  position: absolute;
  left: 50%;
  right: 0;
  top: 50%;
  z-index: 10;
  -webkit-transform: translate(-50% , -50%);
  transform: translate(-50%, -50%);
  padding: 3em;
  border-radius: 	12px;
  background-color: rgb(255, 255, 255);
  text-align: center;
  max-width: 40%;
  margin: auto;
  box-shadow: rgba(0, 0, 0, 0.45) 0px 2px 10px;
  transition: .20s ease-in-out;
  opacity: 0;
}

.modal.is-open {
    visibility: visible;
    opacity: 1;
}

.modal__close {
    position: absolute;
    right: 0;
    top: 0;
    background: white;
    border: none;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    line-height: 30px;
    line-heght: 7px;
    cursor: pointer;
    margin: -7px -7px 0 0;
}

.modal-btn {
    background: white;
    padding: 14px 20px;
    color: #505763;
    cursor: pointer;
    display: inline-block;
    font-weight: bold;
    text-transform: uppercase;
    font-size: 1.2em;
    border-radius: 6px;
    border: 1px solid transparent;
    transition: .15s ease-in-out;
}

.modal-btn:active {
    background-color: #cecece;
}

.vert-mid {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);//Here is the magic
}

 

The JavaScript

In programming, we need to break things apart. I love planning, and that’s why we are going to plan the modal on how we are going to achieve the desired effect!

Planning

Okay, we want to make a modal. We want it to be hidden, and how only when a button is clicked.A modal should pop up on click of a button. When we do that, we want an overlay behind the modal as well, that get’s shown when the modal does.

We want the modal to have an ‘X’ that will close the modal. Which means that on pressing the ‘X’, the modal and the overlay needs to disappear. When we click on the overlay, we want the modal and the overlay to disappear as well. What will happen if we press the button that opens the modal again? We want to open the modal again and repeat the functionality.

Now that we got the planning out, we can start to figure out the code to achieve this.

Setting up the project

A good way to not have a blank mind is to make a structure first, or just anything so we can work with something.

Variables

We want to select the things we will be working with, so that is the button and the modal – maybe more things in future. Let’s write Variables.

//Variables
var modal = document.querySelector('.modal');
var modalBtn = document.querySelector('.modal-btn');
var modalCloseBtn = document.querySelector('.modal__close');

Alright, we got the modal, we got the ‘modal-btn’ which opens the modal, and we have the modalCloseBtn button that closes the modal when we click it.

What about the overlay? Hmmm… There are many ways to go about it, but I will create the element dynamically and then insert it into the HTML with javascript. I will want to append it to the body so it’s above everything.

Let’s add this code to our variables:

var body = document.querySelector('body');

Now, let’s create the modal element.

We want to make a variable, and we want to ‘createElement’, let it be a div.

var modalOverlay = document.createElement('div');

Now we have a div that’s totally alone on it’s own. Let’s add a class to it, we can do that by selecting the modal, and using the ‘className’, then specifying what class we want to add.

modalOverlay.className = 'modal-overlay';

By now you should have these variables:

var modal = document.querySelector('.modal');
var modalBtn = document.querySelector('.modal-btn');
var modalCloseBtn = document.querySelector('.modal__close');
var body = document.querySelector('body');
var modalOverlay = document.createElement('div');
modalOverlay.className = 'modal-overlay';

Event Listeners

I always like to write the event listeners first, because that way we will know what to do, and how many functions to write.

We want to do something when we click on the button to show the modal, click on the modal overlay, and the ‘X’ to close the button.

Let’s create a function that opens the modal, and closes. We will also need to pass in the event since we are going to activate them with the click – which is an event.

function openModal(e) {

}

function closeModal(e) {

}

Next, we don’t know what sort of button will it be, it might be an anchor tag, or it might refresh the page. We don’t want any of that, so we will prevent it from doing it.

We can do so with the ‘preventDefault()’ function. Before that, we need to pass in the ‘e’, since it will be happening on the event.

The ‘e’ can be anything, however in this case the ‘e’ is short for ‘event’, so we could write that, but for the simplicity sake, let’s keep the ‘e’ as that’s widely used terms – better get used now than later.

‘e.preventDefault()’

Opening the modal

Now, what do we want to do in the openModal function? We want to show the overlay and the modal itself.

Let’s select the overlay and the modal and add in the appropriate class.

modalOverlay.classList.add('is-open');
modal.classList.add('is-open');

Simple!

Wait wait wait, the overlay doesn’t show up. Can you guess why?

We created the HTML in the variables if you remember, but we didn’t include it in the HTML. Out created HTML tag, div, with the class name of ‘modal-overlay’, is inside our JavaScript file! It’s trapped!

To get it untrapped, we need to get the document, get the body, since that’s where we want to append it, and say what we want to append.

document.body.appendChild(modalOverlay);

The way appendChild works is that it moves an element to somewhere. We would use this to make a list and append the new item, perhaps we would need to use ‘node’ before the append, it depends on what we are doing.

Now, we want to specify what we want to append. THe modalOverlay. What is modalOverlay?

Remember we created the element in the variable? We created this:

<div></div>

After we added a class to it, we have this:

div class="modal-overlay"></div>

So now with the appendChild function, we are basically saying to append that.

You should have the following code:

function openModal(e) {
    e.preventDefault();
    modalOverlay.classList.add('is-open');
    modal.classList.add('is-open');
    document.body.appendChild(modalOverlay);
}

Now when we click the button, the modal and the overlay will appear.

Closing the Modal

In the closeModal function, we want to do a similar thing to what we did here.

Before we added the class to the modal to show, and now we want to remove it. Before we added the class to the modal-overlay, and now we want to remove it.

Can you guess how to do it? What is the opposite of ‘insert’ or ‘add’?

You guessed it right! It’s ‘remove’!

function closeModal(e) {
    modalOverlay.classList.remove('is-open');
    modal.classList.remove('is-open');
}

There is one more thing, remember when we added the element ‘append’? The element is still there. Depending on how the CSS is written, I would remove it. Sometimes you might get this invisible layer that the user can’t click anywhere because the overlay covers the entire website.

To remove it, we do the exact same thing! We ‘removeChild’.

document.body.removeChild(modalOverlay);

You did it!

Here is the full code:

window.onload = function() {
    
    //Variables
    var modal = document.querySelector('.modal');
    var modalBtn = document.querySelector('.modal-btn');
    var modalCloseBtn = document.querySelector('.modal__close');
    var body = document.querySelector('body');
    var modalOverlay = document.createElement('div');
    modalOverlay.className = 'modal-overlay';
    
    function openModal(e) {
        e.preventDefault();
        modalOverlay.classList.add('is-open');
        modal.classList.add('is-open');
        document.body.appendChild(modalOverlay);
    }
    
    function closeModal(e) {
        modalOverlay.classList.remove('is-open');
        modal.classList.remove('is-open');
        document.body.removeChild(modalOverlay);
    }
    
    modalCloseBtn.addEventListener('click', closeModal);
    modalOverlay.addEventListener('click', closeModal);
    modalBtn.addEventListener('click', openModal);
    
}

What can you do to improve it?

On the ‘esc’ key, make the modal disappear.

Add accessibility.

Make the code for multiple modals. Perhaps use JS prototyping or OOP JS.

Conclusion

Now you have learned how to do a basic modal. Keep practicing and you’ll get better at it!

If you have any suggestions, or improvements, comment them below!

How did your modal ended up? 🙂

 

And as always, Happy Coding! 🙂

 

Meet the author

Meet the author

Aurelian Spodarec

Front-end WordPress developer that blogs about web development. I like using the right tools for the job. In my spare time, I enjoy cooking healthy food and then eating it. Delicious!

Comments