DEV Community

Cover image for How to build a Modal
Jay Cruz
Jay Cruz

Posted on

How to build a Modal

A brief tutorial on how to build a modal using Javascript, HTML, and CSS.

What’s a modal?

Modals are pop-up windows or dialog boxes that display some sort of content above everything else on a web page. They usually are triggered by an event such as clicking on a button. They can also pop up automatically (which can be very annoying at times!). We’ve all probably come across one at some point while browsing the web. Many times they will display some content asking you for your email or to sign up for some sort of promotional offer. Well, today we won't be signing up for anything, we’ll be building one ourselves!

Building a Modal

To build our modal we’ll be using plain ol’ Javascript, HTML, and, CSS. To start off we’re going to set up our HTML template. We’ll need several parts to make up our modal. An outer div element that we’ll label with the id overlay. This will be the window our modal box will sit on top of. The modal will contain all of the main content we want to be displayed once the modal opens, including a close button to hide the modal. We also need a button to actually trigger the modal to be opened. Lastly, we’ll link our CSS and Javascript files.


Now we can add some styling to make our modal more visually appealing by styling our buttons and the actual modal itself.

Let’s see what our closed modal is looking like so far.

Green Contact Me button

Looks great! Now we just have to hook it up using Javascript. We’ll need to listen for click events for when a user clicks the Contact Me button and when they close the modal.


This sets up the functionality for opening and closing our modal. Now when a user clicks on the Contact Me button our user will see the modal with all the contact details displayed.

Modal with contact details

Summary

Modals are meant to capture a user’s attention. When modals are triggered everything else on the page becomes temporarily deactivated. This creates an immediate focus on the information the modal is presenting. Sometimes this can enhance the user experience, other times it can do the exact opposite. It all depends on the use case and whether or not the modal presents useful content that’s relevant to the user.

Learn more about Modals

Discussion (1)

Collapse
supportic profile image
Supportic

This example raised some questions:

  1. Why do you wrap your listeners around functions?
  2. Why do you hide the H1 headline when the modal is covering it?
  3. Why do you declare the variable modal if its never used?

For future research:

  • try to make modals more accessible [ref]
  • Since your link "contact me" is rather an action than a link to something statically, the use of a button is prefered.