More articles

The simplest way to create dynamic modal pop-ups in JavaScript

Written by
Published on

Modal windows are an important UI/UX tool when it comes to pretty much any type of application, whether web, mobile or even your local ATM machine. What is a modal window? Good question.

A modal window is any popup style window that gets the users attention and normally asks them to agree or to disagree on something before closing itself out.

Ideally, you want to use a modal window in a few different situations, such as:

- Get the users attention
- Have the user make a choice
- Prevent the user from continuing until some action has been taken
- Hidden menu panels

It looks relatively straight forward. You have a <div> element with content inside of it, invisible at first, appearing when something triggers it. Normally you have some form of transparent overlay behind it that prevents the users from doing anything else on the page. And lastly, it goes away once that action has been completed or when the user decides to close it out.

In this article I will be going over how to turn any div into a modal window by adding a single class and how to trigger it with a single function. Write once, run everywhere is the motto that I code by. I'd like to take credit for that, but I believe it is also Java's motto as well.

Step 0. The modal window

Let's start off with designing the modal window itself. This can be tricky, because sometimes you want a very wide and tall window and other times you might prefer a small and concise one. But you always want it relatively centered on the screen. We can go with an in-between default styling to start things out, and you can tweak specific properties if needed later on.

    .modal {
    position: fixed;
    top: 10%;
    padding: 40px 50px;
    border-radius: 8px;
    background-color: white;
    z-index: 60000;
    width: 400px;
    min-height: 100px;
    display: none;
    left: 50%;
    margin-left: -200px;
    max-height: 80%;
    box-sizing: border-box;
}

    .modal.on {
        display: block;
    }
    

The modal window is 'hidden' by default, and displayed once again by adding the 'on' class to that particular element. You can add the 'modal' class to any element that you want to behave as a modal window in your code.

<div class='modal'>
	Hello world
</div>

Step 1. Creating the overlay

Let's start by creating the transparent background that you will see behind the active modal window. This will be injected onto the page at the very end of the body tag. The main function that will handle the logic, will accept a single argument and that will be the id of the div that you are targeting.

        
function modal(id)
{
    let el = document.getElementById(id);  // can also use a query selector
    let body = document.querySelector("body");
    let bg = document.createElement("div");
    bg.className = "modal-js-overlay";
    
    body.appendChild(bg);
}

In the code above, the class modal-js-overlay will handle the actual work of making the bg element appear behind all of the other elements. The CSS itself is the following:

.modal-js-overlay {
    background: #444;
    opacity: .8;
    position: fixed;
    top: 0px;
    width: 100%;
    height: 1000px;
    z-index: 20000;
    left: 0px;
}

2. Creating the 'close' button

Next up, let's create the button that will toggle off the modal window. You might also prefer to have modal windows that are not closable. These would be for mandatory tasks that a user must accomplish before moving forward. But for the sake of simplicity, this example will be closeable.

You can continue to add the following to the modal() function from above.

    let close = document.createElement("span");
    close.className = "modal-js-close";
    close.innerHTML = "x";

close.addEventListener('click', function () { let overlay = body.querySelector(".modal-js-overlay"); let closebtn = parent.querySelector(".modal-js-close"); body.removeChild(overlay); el.classList.remove('on'); el.removeChild(closebtn); });

Jumping in to the 'click' event, closing the modal will come down to a few things. The first being removing the overlay that got dynamically created. Secondly, removing the close button as well. And thirdly, hiding the modal element by removeing the 'on' class.

You can use the following CSS to style the close button:

.modal-js-close {
    position: absolute;
    bottom: 0px;
    right: 0px;
    background: black;
    color: white;
    border-radius: 50%;
    height: 20px;
    width: 20px;
    text-align: center;
    padding: 1px;
    top: -10px;
    right: -10px;
    box-shadow: var(--box-shadow);
    cursor: pointer;
    font-size: 12px;
    font-weight: bold;
}

Closing the modal window with code

Modal windows normally don't just close when the user exits out of them however. Most of the time they close are the user has completed some type of action, such as filling out a form or hitting the right call to action button.

The following function can be called to exit out of the pop at any time and is essentially the same action that you will perform when closing out with the 'close' button from above.

function modaloff(id) {
    let body = document.querySelector("body");
    let el = document.querySelector(id);
    let overlay = body.querySelector(".modal-js-overlay");

    el.classList.remove('on');
    body.removeChild(overlay);
}

Lastly to use the functions, simply call the modal() function passing in any DOM element with the 'modal' class. All of the required 'modal' style elements will get created. And when completed, just call the modaloff() method to close.

<div class='modal' id='modal1'>Hello world</div>


<script>
	function showmodal()
	{
		modal('modal1'); // show
		modaloff('modal1'); // hide
	}
</script>

This code is simple, but gives you full control of how you render and choose to display modal pop-ups in your future products. I hope you found that useful. And feel free to let me know what improvements, additions, features, etc you would want to see added.

- Walt

Land your next big coding job. Search through 1000's of job listings.
X

Discussion / Comments / Questions

No messages posted yet

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post comment