How to Build a Modal with JavaScript

It's probably happened to you before: you unintentionally attempted to perform an action on a webpage, but luckily got a pop-up window asking you to confirm your decision.

This pop-up window is called a modal. It's a web page element that pops up and displays in front of other page content.

You can use modals for doing things like storing information you don't want to immediately see on a webpage, creating navigation menus, adding call-to-action elements, and more.

An excellent example is the modal that appears on Twitter when you attempt to close the compose tweet menu.

Twitter warning modal window

You can also use modals for other things like creating call-to-action elements, navigation menus, newsletter widgets, and more.

As a web developer, knowing how to build a modal can be an handy skill to have. In this tutorial, I'll walk you through the process of how you can create a simple modal using HTML, CSS, and JavaScript.

Here's a screenshot of what we’ll be building:

A modal built with html, css and javascript

The steps are very easy to follow so you can customize the modal or build your own from scratch – it’s entirely up to you. At the end of this article, I'll provide the codepen file so you can play around with it.

Step 1 – Add the Markup

Alright, let's get started with the HTML.

First, you'll add a section element and give it two classes, modal and hidden. Under this element, you’ll also have a <div> element with a class of overlay and hidden . Then finally, you’ll add a <button> element with a class of btn and btn-open.

Here’s what that looks like:

  • The section element with a class of modal will serve as your modal container.
  • The div with the class of overlay will serve as your overlay element. This is the dark blurred background you see when the modal is open.
  • The button with the class of btn and btn-open will serve as your modal button so it fires up our modal when you click this button.

Now inside of your modal, add the markup, and also add the X button for closing the modal. This button will be assigned a btn-close class.

So here’s what your complete markup will look like at the end:

Important ⚠️ Take note of the hidden class added to the modal and the overlay element. This is very important because you'll target these classes to hide your modal and overlay using CSS.

Here's the output:

complete-markup

Step 2 – Style the Modal

Let's start by resetting the default margin and padding of every element on the page, and then center both the modal and open-modal button.

Now jump over to your CSS and add the following styles:

The next step is styling the modal container itself and the elements inside the container. This process is a bit lenghty so I’ll just copy and paste the styling here and then explain it a bit after:

And here's the output:

complete-modal-style

What you did was style the modal element and then position it using the absolute property. This works because you added a position relative property to the body element earlier.

You also styled the elements inside of the modal, but I won’t go deep into the details of that because that is not completely important to us here.

Step 3 – Add the Overlay

For the overlay, you want to position it over the entire page with a subtle dark background and blur.

Since you have the position relative to the body element, you can use the position fixed property to add the overlay over the body element. You'll overlay it 100% of the viewport width and height.

overlay

The overlay works, but you only want it to affect the body element and not the modal. To fix this, add a higher z-index property to the modal container.

Now the modal should be on the overlay and not behind it.

modal

You've successfully created the modal and added an overlay behind it! But you don't want to show the modal, at least not until the open-modal button is clicked.

To hide it, you need to target the .hidden class you added earlier to the modal and overlay element in your CSS. You'll also give it a display of none.

Now only the button is showing on the page. You can now work on the modal functionality using JavaScript.

Step 4 – Add Modal Functionality

Before we proceed, I believe it is best to explain how the modal works. Remember how you used the hidden class to hide the modal and overlay? To add or remove this class from the elements, you'll use the DOM's classList element.

But first, you need to select your classes using the DOM's querySelector method and store them in variables so they are reusable.

How to Open the Modal

In other to show the modal, create a function called openModal . Inside this function, you'll use the DOM classList property which takes in different methods like .remove() and .add() to remove the hidden class from the modal and overlay .

And then you can use an eventListener to tie this function to the open modal button openModalBtn . That way, anytime this button is clicked, the function is executed, which shows the modal.

Now when you click on the open modal button, this will remove the hidden class from the modal element and you can see your modal.

How to Close the Modal

For closing the modal, you’ll also create a function called closeModal . Inside the function, use the .add() method to add back the hidden class you removed.

The classList property also has an add() method which you'll use to add the hidden class back when you click the closeModal button. Just like you added an eventListener to the button to close the modal, you'll do the same to the x button – but this time, you'll add the hidden class back.

To close the modal, add an eventListener to the close modal button to execute the function you just wrote now.

Now when you click the close button, the function will add back the hidden class to the modal and overlay components, thus closing the modal.

Here's the output

Usually, modals are also closed when you click outside of the modal container or on the body of the webpage. To do that, add an eventListener to close the modal when you click on the overlay.

How to Close the Modal on Key Press

In addition to closing the modal when you click the close button or the overlay, you can also attach an event listener to watch for keyboard events.

In this instance, you want the modal to close when you press the Escape key, much like in the Twitter compose modal example.

But this time the type of event you want is not the “click” event – you want to use the “keydown” event to execute your function.

Next up, you'll write a condition that checks if the current key pressed is the Escape key and the modal does not contain the hidden class. So it’s open, and you want to execute the closeModal function (in essence, close the modal).

Now when the modal is open and you hit the <kbd>Esc</kbd> key, it will close the modal.

And with this, you’ve successfully created a modal component with HTML, CSS, and JavaScript and it works just as intended. 🥳

Here’s the codepen file to test this modal in action:

I sincerely hope you found this post interesting or useful. If you did, kindly share with your friends or subscribe to my blog so you won't miss any future postings. Thanks for reading.

GitHub | Twitter | Blog | Portfolio

Software developer specializing in frontend development and open-source

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • CSS Tutorial
  • CSS Exercises
  • CSS Interview Questions
  • CSS Selectors
  • CSS Properties
  • CSS Functions
  • CSS Examples
  • CSS Cheat Sheet
  • CSS Templates
  • CSS Frameworks
  • CSS Formatter
  • Web Development

Related Articles

  • Solve Coding Problems
  • How to strike through text when checking a Checkbox using HTML CSS and JavaScript ?
  • Design a Nested Chat Comments using HTML CSS and JavaScript
  • HTML Registration Form
  • Word and Character Counter using HTML CSS and JavaScript
  • Word Scramble Game using JavaScript
  • How to make a Toast Notification in HTML CSS and JavaScript ?
  • How to Create Tags Input Box in HTML CSS and JavaScript ?
  • Multiplication Quiz Webapp using HTML CSS and JavaScript
  • Building a Daily Motivational Quotes - Google Chrome & Microsoft Edge Extension
  • Price Range Slider with Min-Max Input using HTML CSS and JavaScript
  • How to create Hex color generator using HTML CSS and JavaScript ?
  • JavaScript Pair Game
  • Create a Length Converter using HTML CSS and JavaScript
  • Word Guessing Game using HTML CSS and JavaScript
  • How to Change CSS Properties using JavaScript EventListner Methods ?
  • Scrollspy using HTML CSS and JavaScript
  • Create a Timeline using JavaScript
  • Create a Sortable and Filterable Table using JavaScript
  • Build an Expense Tracker using JavaScript

How to Create a Modal Box using HTML CSS and JavaScript ?

In this example, we will learn how to create a Modal Box using HTML , CSS , and Javascript . A modal is a dialog box that is displayed on top of the screen. We will be creating a modal using HTML, CSS, and JavaScript.

Approach: First, we will create a button, and when the user clicks on the button, the modal box will open. A click event listener will be attached to this button so that when it is clicked our modal opens up. The modal will have two parts, the overlay and the modal body and the modal initially will be hidden by setting the display as none . The Modal’s body will have a title, content, and a button to close the Modal. Additionally, this modal can be closed by clicking on the overlay part of the modal as well. Click event listeners will be attached to the close button inside the modal and the overlay wrapper so that whenever these two are clicked we will again hide the modal by using the display none property.

Example: In this example, we will use the above approach.

Modal using Javascript,HTML and CSS

Please Login to comment...

  • CSS-Questions
  • HTML-Questions
  • JavaScript-Questions
  • Web Technologies
  • mansigeekso9ii

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How To Create a Modal Popup Box with CSS and JavaScript

  • #javascript

How To Create a Modal Popup Box with CSS and JavaScript

In this tutorial, we learn how to make a modal with CSS and JavaScript . Our goal is to create a lightweight and simple modal popup box that does not use any third-party libraries and is cross-browser compatible. We will be using vanilla JavaScript without jQuery. Because we will be building it from scratch, we will have full control over how it looks and functions.

Introduction

Modal popups are used pretty frequently on the web. Some popular uses of them include driving newsletter sign ups, displaying notifications/alerts, and handling register and login forms.

Our modal will be generic which means you will be free to use it for whatever purpose you'd like. Here's what they will look like once finished:

how to create html modal

You can view a live demo of the finished product before continuing on. Now, let's get started on building this!

HTML Markup

Let's start with the HTML markup for the modal.

We have three different components here in the markup.

First, we have a simple button which, when clicked on, triggers the modal to open. Then we have the modal's parent container which houses the modal. Finally, we have the content that will go inside the modal, plus a close button.

To keep things simple, the only content inside the modal is an h1 tag with some text.

These are the styles we will apply to make our modal look nice and pretty.

The styles here should be pretty simple, but here's a great class on CSS if you need a refresher.

Let's break down what we're doing.

The styles for the modal class makes it so that it creates a semi-transparent dark background color behind the modal when it is active. We stretch it to 100% width and height and set its visibility to hidden so that it doesn't appear before the user clicks the button.

Then with the modal-content class, we position the actual modal in the center of the screen, with some visual goodies like a border-radius and some padding .

To allow us to close the modal in an elegant way, we have a close button that is just a nicely styled X button at the top-right corner of the modal. We also have a :hover state for the close button so that it changes color when the user hovers over it.

Finally, we have our class that handles styling the modal when it is opened.

JavaScript Code

To make our modal popup actually work, we will be using a very tiny amount of pure, vanilla JavaScript. Again, we don't want to use any third-party libraries.

We set three click listeners here:

  • When the trigger is clicked, we want to show the modal.
  • When the close button is clicked, we want to hide the modal.
  • When the dark background is clicked, we want to also hide the modal.

Now if we were to press the trigger or the close button, the modal should smoothly animate between the states. It's all about the pretty animations. 😍

Again, you can click here for a live demo of what we created, or use the live editor below!

Modal boxes are universally popular and now you have an easy implementation to use for yourself that is light-weight and uses no third-party libraries like jQuery. You can use this modal for newsletters, sign-ups, or anything else you want! Hopefully you will enjoy the results and find it useful.

Happy coding and thanks for reading!

how to create html modal

  • Privacy Policy
  • Terms of Service

How to Build Modals Easily With the HTML Dialog Element

Get to grips with the HTML dialog element with this guide to modals.

Dialogs and modals are integral parts of most web applications. While building them by hand is not a complex task, it's one that quickly becomes tedious for any web developer. The usual alternative to building them by hand is to use a component built by someone else.

There are a couple of problems with this approach, though. There are so many options, it becomes hard to know which component would be best to use, and customizing the appearance of such components can sometimes be just as tedious as building a dialog by hand. Fortunately, there's another alternative: the HTML dialog element.

What’s the Dialog Element?

The HTML dialog element is a built-in HTML tag (like div or span), that allows developers to create custom dialogs and modals. The dialog element has been around in Chrome and Opera since 2014, but only recently became supported by all major browsers.

Why Use the Dialog Element?

The primary reason to use the dialog element is convenience. It makes it easy to build dialogs that can either appear inline or show up as modals, with nothing more than a single HTML tag and a few lines of JavaScript.

The dialog element removes the need to build and debug a custom dialog, or import someone else's component. It is also very easy to style with CSS.

Browser Support for the Dialog Element

Unfortunately, browser support for the dialog element could be better. It's supported in the latest versions of all major browsers as of March 2022, with some caveats.

Any Firefox browser older than Firefox 98 will only support it if it's manually enabled in the browser settings, and any Safari version earlier than Safari 15.4 doesn't support it at all. Full browser support details are available on caniuse .

Thankfully, this doesn't mean the dialog element is unusable. The Google Chrome team maintains a polyfill you can find on Github for the dialog element that provides support for it even on browsers where it isn't natively supported.

In its current form, the dialog element can have accessibility issues, so it might be more suitable to use a custom dialog component like a11y-dialog in production applications.

How to Use the Dialog Element

To demonstrate how to use the dialog element, you'll be using it to build a common website feature: a confirmation modal for a delete button.

All that's required to follow along is a single HTML file.

1. Set Up The HTML File

Start by creating the said file and naming it index.html.

Next, establish the structure of the HTML file and provide some basic meta-information about the page, so it renders properly on all devices.

Type the following code into index.html:

That's all the setup necessary for this project.

2. Writing the Markup

Next, write the markup for the delete button, as well as the dialog element.

Type the following code in the body tag of index.html:

The HTML above will create:

  • A delete button.
  • The dialog element.
  • Two buttons inside the dialog.

If index.html is open in your browser, the only element visible on the screen will be the delete button. This doesn't mean there's anything wrong, the dialog element simply requires a bit of JavaScript to become visible.

3. Adding JavaScript

Now, write the code that will open the dialog when a user clicks the delete button, as well as code to allow the dialog to close.

Type the following in the script tag of index.html:

This code uses the querySelector method to get references to the buttons and the dialog. It then attaches a click event listener to each button.

You might be familiar with event listeners in JavaScript, which you can use yourself . The event listener attached to the delete button calls the showModal() method to display the dialog when the button is clicked.

Each button inside the modal has an event listener attached to it which uses the close() method to hide the dialog when they are clicked.

Even if there is no JavaScript that calls the close() method in the code, users can also close the modal by pressing the escape key on their keyboard.

Now that this JavaScript is in place, if a user clicks the delete button, the modal will open, and clicking the yes or no button will close the modal.

This is what the opened modal should look like:

a basic confirmation modal

One thing of note is that the dialog element already comes with some styling, even though there's no CSS in index.html. The modal is already centered, it has a border, the width is limited to the content, and it has some default padding.

Users can't interact (click, select) with anything in the background while the modal is open.

The dialog element can also display itself as part of the flow of the page instead of as a modal. To try it out, change the first event listener in the JavaScript like so:

The only thing that has changed in this code is that the code is calling the show() method, instead of the showModal() method. Now, when a user clicks on the delete item button, the modal should open inline like this:

an plain inline dialog

4. Add Styling

Next, customize the look of the dialog and its background by writing CSS.

The CSS will reduce the border of the dialog, limit its maximum width, and then darken the background, as well as add a little styling to the buttons.

Styling the dialog itself is straightforward, but the backdrop pseudo class is necessary to add styling that targets the background of the dialog.

Paste the following code in the style tag of index.html:

When the dialog is open, it should now look like this:

a minimal modal dialog

And you've built a fully functional dialog.

The Dialog Element Is a Great Way to Build Modals

Using the HTML dialog element that recently gained support in all major browsers, web developers can now build fully functional, easily customizable modals and dialogs with one HTML tag and a few lines of JavaScript and without needing to rely on a third party solution.

The dialog element has a polyfill maintained by the Google Chrome team, that allows developers to use dialog in browser versions that don't support it.

DEV Community

DEV Community

Adetutu Oluwasanmi

Posted on Jun 24, 2023

How to Implement a Custom Modal with CSS

Introduction, prerequisite, step-by-step process on how to implement a custom modal with css.

Modal (also known as dialog boxes or popups) is a UI (User Interface) component that is displayed on top of the main content on a web page. In this article, we will explore how to implement a custom modal using CSS.

  • Basic JavaScript

STEP 1: Create the HTML structure

In this step, we will start by setting up the basic HTML structure for the main page and the modal.

STEP 2: Style the page and the modal

Next, we will use CSS to style the main page, modal, and add features such as a close button, animations, and responsive styles.

STEP 3: Add JavaScript for interactivity

Lastly, we will add JavaScript to control the visibility of the modal component. We will set up event listeners on various elements to handle the opening and closing behaviour of the modal component.

GitHub Link

By following the step by step guide outlined above, you can create a custom modal using CSS and also customize the content, styles, animations, and responsiveness according to your design preferences.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

phuocng profile image

Implement the Singleton pattern

Phuoc Nguyen - Feb 19

marciopolicarpo profile image

5 sites para se manter 'afiado' em JS

Marcio Policarpo - Feb 6

adhikareeprayush profile image

The Ultimate Roadmap to a Full-Stack Developer

Prayush Adhikari - Feb 22

webbricks profile image

Landing Page vs Website: What Are the Differences?

Web Bricks - Feb 5

Once suspended, adetutu will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, adetutu will be able to comment and publish posts again.

Once unpublished, all posts by adetutu will become hidden and only accessible to themselves.

If adetutu is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Adetutu Oluwasanmi.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag adetutu:

adetutu consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging adetutu will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

CodeShack

Interactive Modals with JavaScript

Interactive Modals with JavaScript

The interactive modal JS class will enable you to seamlessly implement modals on your website, whether it be a confirmation, alert, or prompt modal. Dynamically create and autogenerate modals with minimal configuration.

The JS class is lightweight and designed to be incorporated into any website. There are no third-party dependencies required, such as jQuery or Bootstrap.

  • Introduction
  • Stylesheet (CSS3)
  • JavaScript Class
  • Autogenerate Modals
  • Dynamic Modals
  • Confirmation Modal
  • Alert Modal
  • Prompt Modal

1. Introduction

Modals appear above the content on a website and are usually triggered with user interactivity, for example, when the user clicks a button. In addition, they deactivate all other page content when they're open and the user must engage with the modal to return to the page content.

You can use the class to replace the native popup boxes in JS, which are not user-friendly in modern web apps. There are methods that will enable you to create confirmation, alert, and prompt boxes, with minimal lines of code.

2. Stylesheet (CSS3)

The stylesheet will structure our modals and give them an elegant look.

In the above stylesheet, we leverage transitions to create an animation effect when the modal opens (zoom, slide, etc). It will give the user a better experience when interacting with the modals.

3. JavaScript Class

The JS class will enable you to create an unlimited number of modals and leverage the popup methods that I've implemented that can replace the native browser popup boxes.

You can use pure HTML to create modals as opposed to dynamically creating them with JS. I will show you how in the next section.

4. How to Use

In this section, I'll provide examples of how you can use the modal class.

4.1. Autogenerate Modals

The following HTML code will create two new modals and anchor links to open them:

To initialize these modals, you need to execute the following JS method:

Which you can do at the end of the document (before the body closing tag):

When you click the Open Modal button, you should see the following:

Interactive Modal

4.2. Dynamic Modals

To create dynamic modals, you need to create a new instance of the Modal class:

You can customize with modal options as seen in the code example above. The onOpen and onClose functions are event handlers for the modal.

To open the modal, you can do:

And to close the modal, you can do:

Or you can attach a button element to the modal with the class close .

You can also update the modal content like so:

To add an existing modal in the DOM, you can specify the element option when declaring a new instance:

4.3. Confirmation Modal

To create a new confirmation modal, you can do:

There is no need to create a new instance of the class as these are static methods.

The confirmation modal will look like the following:

Confirmation Modal

4.4. Alert Modal

You can create a new alert modal with the following:

Which will look like the following:

Alert Modal

4.5. Prompt Modal

To create a new prompt modal (which will allow user input), you can do:

Prompt Modal

If you have any suggestions or feedback regarding the modal class, drop a comment below. Share the article on social media using the buttons below as it will help us create more quality content.

Released under the MIT license. Attribution would be appreciated but is not essential.

About Author David Adams I'm an enthusiastic full-stack engineer who's been in the web development scene for over a decade. I enjoy the creativity I put into my projects and what others bring to the awesome web. My goal is to share my knowledge and help newcomers develop their skills.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

The :modal CSS pseudo-class matches an element that is in a state in which it excludes all interaction with elements outside it until the interaction has been dismissed. Multiple elements can be selected by the :modal pseudo-class at the same time, but only one of them will be active and able to receive input.

Usage notes

Examples of elements that will prevent user interaction with the rest of the page and will be selected by the :modal pseudo-class include:

  • The dialog element opened with the showModal() API.
  • The element selected by the :fullscreen pseudo-class when opened with the requestFullscreen() API.

Styling a modal dialog

This example styles a modal dialog that opens when the "Update details" button is activated. This example has been built on top of the <dialog> element example .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • dialog element
  • Other element display state pseudo-classes: :fullscreen and :picture-in-picture
  • Complete list of pseudo-classes

70+ CSS Modal Windows

Welcome to our collection of CSS modal windows ! In this curated compilation, we have gathered a diverse range of HTML and CSS modal window code examples sourced from reputable platforms such as CodePen, GitHub , and other valuable resources.

With our April 2023 update , we are excited to present six new additions to our collection, ensuring that you have access to the latest and most innovative modal window designs available.

Modal windows are a popular UI element used to display additional content or interactions without navigating away from the current page.

Start exploring our collection now and discover the creative ways to engage your users with visually appealing and functional modal windows.

Related Articles

  • Bootstrap Modal Windows
  • jQuery Modal Windows
  • Tailwind Modal Windows
  • Fernando Cohen
  • April 7, 2022
  • demo and code
  • HTML / CSS (SCSS)

About a code

Modal dialog with backdrop blur. only css.

Compatible browsers: Chrome, Edge, Firefox, Opera, Safari

Responsive: yes

Dependencies: -

Demo image: Giant Buttons

  • Ismail Vittal
  • March 15, 2022

Giant Buttons

Demo image: Modal with Scroll and Faded Text

  • Håvard Brynjulfsen
  • January 13, 2022

Modal with Scroll and Faded Text

A simple way to create a modal that never exceed the viewport's height and allows for scroll inside.

  • July 13, 2021

Pop-up without JavaScript

Demo image: CSS Window / Modal

  • Nacho Toledo
  • June 28, 2021

CSS Window / Modal

  • Niels Voogt
  • January 10, 2021

Details Modal

By nesting a modal inside a details element it is automaticly shown when the details is opened. And by nesting the overlay inside the summary element, we can use that to trigger a close.

  • Mark Faulkner
  • December 18, 2020

CSS Only Popup

Demo image: Cookies Popup UI Design

  • Igor Milenkovic
  • November 1, 2020
  • HTML / CSS (Less)

Cookies Popup UI Design

Responsive: no

  • Homer Gaines
  • August 28, 2020

CSS Modal Using :target Selector

This example shows how to open a modal window using HTML and CSS only.

  • Ivan Grozdic
  • July 10, 2020

Pure CSS Modal - #15

Dependencies: unicons.css

  • April 27, 2020

CSS-only Modal

Dependencies: font-awesome.css

  • Abubaker Saeed
  • August 26, 2019

CSS Modals v2

The second version of my previous pen(CSS Modal). In this one, I showed that there are three different modals with their own unique ids and I am using different links to open and close them.
  • August 24, 2019

CSS modal (using :target).

  • Larissa Rabello
  • April 22, 2019

Sign Up Modal

Dependencies: bootstrap.css

  • Lasse Diercks
  • January 26, 2019

About the code

Simple popup in HTML and CSS.

  • Mikael Ainalem
  • November 27, 2018

Material UI Popup

Easing is not easy! However, with the right easing from the Material Design guidelines, you get punchy and snappy animations.

  • Timothy Long
  • December 19, 2018

Basic CSS-only modal window.

  • Mert Cukuren
  • October 1, 2018
  • HTML / CSS (SCSS) / JavaScript (Babel)

Login Modal

Modal login form in HTML, CSS and JavaScript.

  • Thibaud Goiffon
  • September 1, 2018

Fancy Pop-Up

Demo image: Pop-up Design

  • March 15, 2018

Pop-up Design

Pure CSS pop-up design with animation.

  • Blake Bowen
  • February 26, 2018
  • JavaScript (tweenmax.js)

Folding Modal

Folding modal window with HTML, CSS and JS.

Demo image: CSS Popup

  • January 28, 2018

Pure CSS modal window.

Demo image: Super Simple Easy Modal

  • Joshua Ward
  • January 9, 2018

Super Simple Easy Modal

Super simple easy modal with ES6.

Demo Image: CSS Only Popup Animation

  • Stas Melnikov

CSS Only Popup Animation

HTML and CSS popup animation.

  • Chouaib Blgn
  • JavaScript (jquery.js)

PopUp Overlay Animation

Popup overlay using HTML and CSS and JavaScript.

  • Nathan Smith
  • Apr 28, 2022

CTA Modal: How To Build A Web Component

  • 23 min read
  • Apps , HTML , Browsers , JavaScript , Web Components
  • Share on Twitter ,  LinkedIn

About The Author

Nathan Smith is a principal software engineer at Microsoft where he builds incubation projects for the Office of the CTO. He primarily works with CSS, Node, and … More about Nathan ↬

Email Newsletter

Weekly tips on front-end & UX . Trusted by 200,000+ folks.

I have a confession to make — I am not overly fond of modal dialogs (or just “modals” for short). “Hate” would be too strong a word to use, but let’s say that nothing is more of a turnoff when starting to read an article than being “slapped in the face” with a modal window before I have even begun to comprehend what I am looking at.

Or, if I could quote Andy Budd :

A typical website visit in 2022 1. Figure out how to decline all but essential cookies 2. Close the support widget asking if I need help 3. Stop the auto-playing video 4. Close the “subscribe to our newsletter” pop-up 5. Try and remember why I came here in the first place — Andy Budd (@andybudd) January 2, 2022

That said, modals are everywhere among us. They are a user interface paradigm that we cannot simply disinvent. When used tastefully and wisely , I dare say they can even help add more context to a document or to an app.

Throughout my career, I have written my fair share of modals. I have built bespoke implementations using vanilla JavaScript, jQuery, and more recently — React . If you have ever struggled to build a modal, then you will know what I mean when I say: It is easy to get them wrong. Not only from a visual standpoint but there are plenty of tricky user interactions that need to be accounted for as well.

I am the type of person who likes to “go deep” on topics that vex me — especially if I find the topic resurfacing — hopefully in an effort to avoid revisiting them ever again. When I started to get more into Web Components , I had an “a-ha!” moment. Now that Web Components are widely supported by every major browser (RIP, IE11 ), this opens up a whole new door of opportunity. I thought to myself:

“What if it were possible to build a modal that, as a developer authoring a page or app, I would not have to fuss with any additional JavaScript config?”

Write once and run everywhere, so to speak, or at least that was my lofty aspiration. Good news. It is indeed possible to build a modal with rich interaction that only requires authoring HTML to use.

Note: In order to benefit from this article and code examples you will need some basic familiarity with HTML, CSS, and JavaScript.

Before We Even Begin

If you are tight on time and just want to see the finished product, check it out here:

  • CTA Modal Demo page
  • CTA Modal Git repo

Use The Platform

Now that we have covered the “why” of scratching this particular itch, throughout the rest of this article I will explain the “how” of building it.

First, a quick crash course on Web Components. They are bundled snippets of HTML, CSS, and JavaScript that encapsulate scope. Meaning, no styles from outside of a component will affect within, nor vice versa. Think of it like a hermetically sealed “ clean room ” of UI design.

At first blush, this may seem nonsensical. Why would we want a chunk of UI that we cannot control externally via CSS? Hang onto that thought, because we will come back to it soon.

The best explanation is reusability. Building a component in this manner means we are not beholden to any particular JS framework du jour . One common phrase that gets bandied about in conversations around web standards is “ use the platform .” Now more than ever, the platform itself has superb cross-browser support .

For reference, I will be referring to this code example — cta-modal.ts .

Note: I am using TypeScript here, but you absolutely do not need any additional tooling to create a Web Component. In fact, I wrote my initial proof-of-concept in vanilla JS. I added TypeScript later, to bolster confidence in others using it as an NPM package.

The cta-modal.ts file is chunked apart into several sections:

  • Conditional wrapper ;
  • Reusable variables ,
  • Component styles ,
  • Component markup ;
  • Constructor ,
  • Binding this context ,
  • Lifecycle methods ,
  • Adding and removing events ,
  • Detecting attribute changes ,
  • Focusing specific elements ,
  • Detecting “outside” modal ,
  • Detecting motion preference ,
  • Toggling modal show/hide ,
  • Handle event: click overlay ,
  • Handle event: click toggle ,
  • Handle event: focus element ,
  • Handle event: keyboard ;
  • Waits for the page to be ready,
  • Registers the <cta-modal> tag.

Conditional Wrapper

There is a single, top level if that wraps the entirety of the file’s code:

The reason for this is twofold. We want to ensure that there is browser support for window.customElements . If so, this gives us a handy way to maintain variable scope. Meaning, that when declaring variables via const or let , they do not “leak” outside of the if {…} block. Whereas using an old school var would be problematic, inadvertently creating several global variables.

Reusable Variables

Note: A JavaScript class Foo {…} differs from an HTML or CSS class="foo" .

Think of it simply as: “A group of functions, bundled together.”

This section of the file contains primitive values that I intend to reuse throughout my JS class declaration. I will call out a few of them as being particularly interesting.

  • ANIMATION_DURATION Specifies how long my CSS animations will take. I also reuse this later within a setTimeout to keep my CSS and JS in sync. It is set to 250 milliseconds, which is a quarter of a second. While CSS allows us to specify animation-duration in whole seconds (or milliseconds), JS uses increments of milliseconds. Going with this value allows me to use it for both.
  • DATA_SHOW and DATA_HIDE These are strings for the HTML data attributes 'data-cta-modal-show' and 'data-cta-modal-hide' that are used to control the show/hide of modal, as well as adjust animation timing in CSS. They are used later in conjunction with ANIMATION_DURATION .
  • PREFERS_REDUCED_MOTION A media query that determines whether or not a user has set their operating system’s preference to reduce for prefers-reduced-motion . I look at this value in both CSS and JS to determine whether to turn off animations.
  • FOCUSABLE_SELECTORS Contains CSS selectors for all elements that could be considered focusable within a modal. It is used later more than once, via querySelectorAll . I have declared it here to help with readability, rather than adding clutter to a function body.

It equates to this string:

Yuck, right!? You can see why I wanted to break that into multiple lines.

As an astute reader, you may have noticed type='hidden' and tabindex="0" are using different quotation marks. That is purposeful, and we will revisit the reasoning later on.

Component Styles

This section contains a multiline string with a <style> tag. As mentioned before, styles contained within a Web Component do not affect the rest of the page. It is worth noting how I am using embedded variables ${etc} via string interpolation.

  • We reference our variable PREFERS_REDUCED_MOTION to forcibly set animations to none for users who prefer reduced motion.
  • We reference DATA_SHOW and DATA_HIDE along with ANIMATION_DURATION to allow shared control over CSS animations. Note the use of the ms suffix for milliseconds, since that is the lingua franca of CSS and JS.

Component Markup

The markup for the modal is the most straightforward part. These are the essential aspects that make up the modal:

  • scrollable area,
  • focus traps,
  • semi-transparent overlay,
  • dialog window,
  • close button.

When making use of a <cta-modal> tag in one’s page, there are two insertion points for content. Placing elements inside these areas cause them to appear as part of the modal:

  • <div slot="button"> maps to <slot name='button'> ,
  • <div slot="modal"> maps to <slot name='modal'> .

You might be wondering what “focus traps” are, and why we need them. These exist to snag focus when a user attempts to tab forwards (or backwards) outside of the modal dialog. If either of these receives focus, they will place the browser’s focus back inside.

Additionally, we give these attributes to the div we want to serve as our modal dialog element. This tells the browser that the <div> is semantically significant. It also allows us to place focus on the element via JS:

  • aria-modal='true' ,
  • role='dialog' ,
  • tabindex'-1' .

You may be wondering: “Why not use the dialog tag?” Good question. At the time of this writing, it still has some cross-browser quirks. For more on that, read this article by Scott O’hara . Also, according to the Mozilla documentation , dialog is not allowed to have a tabindex attribute, which we need to put focus on our modal.

Constructor

Whenever a JS class is instantiated, its constructor function is called. That is just a fancy term that means an instance of the CtaModal class is being created. In the case of our Web Component, this instantiation happens automatically whenever a <cta-modal> is encountered in a page’s HTML.

Within the constructor we call super which tells the HTMLElement class (which we are extend -ing) to call its own constructor . Think of it like glue code, to make sure we tap into some of the default lifecycle methods.

Next, we call this._bind() which we will cover a bit more later. Then we attach the “shadow DOM” to our class instance and add the markup that we created as a multiline string earlier.

After that, we get all the elements — from within the aforementioned component markup section — for use in later function calls. Lastly, we call a few helper methods that read attributes from the corresponding <cta-modal> tag.

Binding this Context

This is a bit of JS wizardry that saves us from having to type tedious code needlessly elsewhere. When working with DOM events the context of this can change, depending on what element is being interacted with within the page.

One way to ensure that this always means the instance of our class is to specifically call bind . Essentially, this function makes it, so that it is handled automatically. That means we do not have to type things like this everywhere.

Instead of typing that snippet above, every time we add a new function, a handy this._bind() call in the constructor takes care of any/all functions we might have. This loop grabs every class property that is a function and binds it automatically.

Lifecycle Methods

By nature of this line, where we extend from HTMLElement , we get a few built-in function calls for “free.” As long as we name our functions by these names they will be called at the appropriate time within the lifecycle of our <cta-modal> component.

  • observedAttributes This tells the browser which attributes we are watching for changes.
  • attributeChangedCallback If any of those attributes change, this callback will be invoked. Depending on which attribute changed, we call a function to read the attribute.
  • connectedCallback This is called when a <cta-modal> tag is registered with the page. We use this opportunity to add all our event handlers. If you are familiar with React , this is similar to the componentDidMount lifecycle event.
  • disconnectedCallback This is called when a <cta-modal> tag is removed from the page. Likewise, we remove all obsolete event handlers when/if this occurs. It is similar to the componentWillUnmount lifecycle event in React.

Note: It is worth pointing out that these are the only functions within our class that are not prefixed by an underscore ( _ ). Though not strictly necessary, the reason for this is twofold. One, it makes it obvious which functions we have created for our new <cta-modal> and which are native lifecycle events of the HTMLElement class. Two, when we minify our code later the prefix denotes they can be mangled. Whereas the native lifecycle methods need to retain their names verbatim.

Adding And Removing Events

These functions register (and remove) callbacks for various element and page-level events:

  • buttons clicked,
  • elements focused,
  • keyboard pressed,
  • overlay clicked.

Detecting Attribute Changes

These functions handle reading attributes from a <cta-modal> tag and setting various flags as a result:

  • Setting an _isAnimated boolean on our class instance.
  • Setting title and aria-label attributes on our close button.
  • Setting an aria-label for our modal dialog, based on heading text.
  • Setting an _isActive boolean on our class instance.
  • Setting an _isStatic boolean on our class instance.

You may be wondering why we are using aria-label to relate the modal to its heading text (if it exists). At the time of this writing, browsers are not currently able to correlate an aria-labelledby="…" attribute — within the shadow DOM — to an id="…" that is located in the standard (aka “light”) DOM.

I will not go into great detail about that, but you can read more here:

  • W3C: cross-root ARIA
  • WHATWG: element reflection ticket

Focusing Specific Elements

The _focusElement function allows us to focus an element that may have been active before a modal became active. Whereas the _focusModal function will place focus on the modal dialog itself and will ensure that the modal backdrop is scrolled to the top.

Detecting “Outside” Modal

This function is handy to know if an element resides outside the parent <cta-modal> tag. It returns a boolean, which we can use to take appropriate action. Namely, tab trapping navigation inside the modal while it is active.

Detecting Motion Preference

Here, we reuse our variable from before (also used in our CSS) to detect if a user is okay with motion. That is, they have not explicitly set prefers-reduced-motion to reduce via their operating system preferences.

The returned boolean is a combination of that check, plus the animated="false" flag not being set on <cta-modal> .

Toggling Modal Show/Hide

There is quite a bit going on in this function, but in essence, it is pretty simple.

  • If the modal is not active, show it. If animation is allowed, animate it into place.
  • If the modal is active, hide it. If animation is allowed, animate it disappearing.

We also cache the currently active element, so that when the modal closes we can restore focus.

The variables used in our CSS earlier are also used here:

  • ANIMATION_DURATION ,
  • DATA_SHOW ,
  • DATA_HIDE .

Handle Event: Click Overlay

When clicking on the semi-transparent overlay, assuming that static="true" is not set on the <cta-modal> tag, we close the modal.

Handle Event: Click Toggle

This function uses event delegation on the <div slot="button"> and <div slot="modal"> elements. Whenever a child element with the class cta-modal-toggle is triggered, it will cause the active state of the modal to change.

This includes listening for various events that are considered activating a button:

  • mouse clicks,
  • pressing the enter key,
  • pressing the spacebar key.

Handle Event: Focus Element

This function is triggered whenever an element receives focus on the page. Depending on the state of the modal, and which element was focused, we can trap tab navigation within the modal dialog. This is where our FOCUSABLE_SELECTORS from early comes into play.

Handle Event: Keyboard

If a modal is active when the escape key is pressed, it will be closed. If the tab key is pressed, we evaluate whether or not we need to adjust which element is focused.

DOM Loaded Callback

This event listener tells the window to wait for the DOM (HTML page) to be loaded, and then parses it for any instances of <cta-modal> and attaches our JS interactivity to it. Essentially, we have created a new HTML tag and now the browser knows how to use it.

Build Time Optimization

I will not go into great detail about this aspect, but I think it is worth calling out.

After transpiling from TypeScript to JavaScript, I run Terser against the JS output. All the aforementioned functions that begin with an underscore ( _ ) are marked as safe to mangle. That is, they go from being named _bind and _addEvents to single letters instead.

That step brings the file size down considerably. Then I run the minified output through a minifyWebComponent.js process that I created, which compresses the embedded <style> and markup even further.

For example, class names and other attributes (and selectors) are minified. This happens in the CSS and HTML.

  • class='cta-modal__overlay' becomes class=o . The quotes are removed as well because the browser does not technically need them to understand the intent.
  • The one CSS selector that is left untouched is [tabindex="0"] , because removing the quotes from around the 0 seemingly makes it invalid when parsed by querySelectorAll . However, it is safe to minify within HTML from tabindex='0' to tabindex=0 .

When it is all said and done, the file size reduction looks like this (in bytes):

  • un-minified: 16,849,
  • terser minify: 10,230,
  • and my script: 7,689.

To put that into perspective, the favicon.ico file on Smashing Magazine is 4,286 bytes. So, we are not really adding much overhead at all, for a lot of functionality that only requires writing HTML to use.

If you have read this far, thanks for sticking with me. I hope that I have at least piqued your interest in Web Components!

I know we covered quite a bit, but the good news is: That is all there is to it. There are no frameworks to learn unless you want to. Realistically, you can get started writing your own Web Components using vanilla JS without a build process.

There really has never been a better time to #UseThePlatform . I look forward to seeing what you imagine.

Further Reading

I would be remiss if I did not mention that there are a myriad of other modal options out there.

While I am biased and feel my approach brings something unique to the table — otherwise I would not have tried to “reinvent the wheel” — you may find that one of these will better suit your needs.

The following examples differ from CTA Modal in that they all require at least some additional JavaScript to be written by the end-user developer. Whereas with CTA Modal, all you have to author is the HTML code.

Flat HTML & JS:

  • a11y-dialog
  • Bootstrap modal

Web Components:

  • web-dialog with @a11y/focus-trap
  • jQuery Modal
  • React Modal
  • Vue.js Modal

Smashing Newsletter

Tips on front-end & UX, delivered weekly in your inbox. Just the things you can actually use.

Front-End & UX Workshops, Online

With practical takeaways, live sessions, video recordings and a friendly Q&A.

TypeScript in 50 Lessons

Everything TypeScript, with code walkthroughs and examples. And other printed books.

How TO - Modal Images

Learn how to create responsive Modal Images with CSS and JavaScript.

Modal Image

A modal is a dialog box/popup window that is displayed on top of the current page.

This example use most of the code from the previous example, Modal Boxes , only in this example, we use images.

Snow

Try it Yourself »

Step 1) Add HTML:

Example explained.

The Trigger/Open Part

Use any element to open the actual modal, e.g. a <button> or an <a> element and specify a unique ID.

The Modal Part

The <div> with class="modal" is a container element for the modal and the div with class="modal-content" is where you put your modal content (headings, paragraphs, images, etc).

The <span> element with class="close" should be used to close the modal.

Step 2) Add CSS:

The .modal class

The .modal class represents the window BEHIND the actual modal box. The height and width is set to 100%, which should create the illusion of a background window.

Add a black background color with opacity.

Set position to fixed; meaning it will move up and down the page when the user scrolls.

It is hidden by default, and should be shown with a click of a button (we'll cover this later).

The .modal-content class

This is the actual modal box that gets focus. Do whatever you want with it. We have got you started with a border, some padding, and a background color. The margin: 15% auto is used to push the modal box down from the top (15%) and centering it (auto).

We also set the width to 400px - this could be more or less, depending on screen size. We will cover this later.

The .close class

The close button is styled with a large font-size, a specific color and floats to the right. We have also added some styles that will change the color of the close button when the user moves the mouse over it.

Advertisement

Step 3) Add JavaScript:

Tip: Also check out Modals and Lightbox .

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. How to Create a Simple Modal with HTML, CSS and JavaScript

    how to create html modal

  2. How to Create a Modal Window For Your Websites

    how to create html modal

  3. How to create the Modal Box Using HTML CSS and Jquery

    how to create html modal

  4. How to Create Modal with HTML, CSS & Javascript

    how to create html modal

  5. How to create a modal with HTML, CSS & JS

    how to create html modal

  6. How to Create a Simple Modal with HTML, CSS and JavaScript

    how to create html modal

VIDEO

  1. MODAL using HTML and CSS

  2. HTML LISTS AND STYLING

  3. Create a Simple Popup Modal

  4. Mosaic Grid Modal

  5. Simple HTML CSS and JavaScript Modal Tutorial

  6. Read more button with Modal using HTML CSS JS Only

COMMENTS

  1. How To Make a Modal Box With CSS and JavaScript

    Learn how to create a modal box with CSS and JavaScript in this tutorial from W3Schools. A modal box is a pop-up window that can display any HTML content, such as text, images, forms, etc. You will also learn how to customize the appearance and behavior of the modal box with different classes and options.

  2. W3.CSS Modal

    Create A Modal. The w3-modal class defines a container for a modal. The w3-modal-content class defines the modal content. Modal content can be any HTML element (divs, headings, paragraphs, images, etc.). ... Use any HTML element to open the modal. However, this is often a button or a link. Add the onclick attribute and point to the id of the ...

  3. How to Build a Modal with JavaScript

    How to Open the Modal. In other to show the modal, create a function called openModal. Inside this function, you'll use the DOM classList property which takes in different methods like .remove () and .add () to remove the hidden class from the modal and overlay. const openModal = function () {.

  4. <dialog>: The Dialog element

    The <dialog> HTML element represents a modal or non-modal dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow. The HTML <dialog> element is used to create both modal and non-modal dialog boxes. Modal dialog boxes interrupt interaction with the rest of the page being inert, while non-modal dialog boxes ...

  5. Modal · Bootstrap

    Learn how to use Bootstrap's modal plugin to create responsive and customizable dialogs for your website. You can display lightboxes, user notifications, or any custom content you want. You can also integrate modal with other Bootstrap components, such as buttons, forms, and cards.

  6. How to Create a Modal Box using HTML CSS and JavaScript

    A modal is a dialog box that is displayed on top of the screen. We will be creating a modal using HTML, CSS, and JavaScript. Approach: First, we will create a button, and when the user clicks on the button, the modal box will open. A click event listener will be attached to this button so that when it is clicked our modal opens up.

  7. Bootstrap Modals

    The .close class styles the close button, and the .modal-title class styles the header with a proper line-height. The .modal-body class is used to define the style for the body of the modal. Add any HTML markup here; paragraphs, images, videos, etc. The .modal-footer class is used to define the style for the footer of the modal. Note that this ...

  8. How To Create a Modal Popup Box with CSS and JavaScript

    First, we have a simple button which, when clicked on, triggers the modal to open. Then we have the modal's parent container which houses the modal. Finally, we have the content that will go inside the modal, plus a close button. To keep things simple, the only content inside the modal is an h1 tag with some text.

  9. A How-To Guide for Modal Boxes with Javascript, HTML, and CSS

    HTML: markup to create the modal element; CSS: styling to determine how your modal looks and appears on the page; Javascript: placing event listeners so the modal appears/disappears depending on ...

  10. How To Use Opacity and Transparency to Create a Modal in CSS

    The .button and .button:hover rules change an <a> element to appear like a large, clickable button. Save your changes to styles.css, then open a web browser. Select the File menu item and then select the Open option. Next, navigate to your project folder and load your index.html file in the browser.

  11. How to Build Modals Easily With the HTML Dialog Element

    Set Up The HTML File. Start by creating the said file and naming it index.html. Next, establish the structure of the HTML file and provide some basic meta-information about the page, so it renders properly on all devices. Type the following code into index.html: <!DOCTYPE html>. <htmllang="en">.

  12. How to Build a Modal Popup Box Using HTML, CSS, and JavaScript

    Build a Modal Popup Box using HTML, CSS and JavaScript. The folder structure for our modal popup box is pretty simple. We would start by creating a folder called modal-box. We would create three files inside this folder: index.html, styles.css, and app.js. We would then link all other files into our index.html as illustrated below:

  13. How to Implement a Custom Modal with CSS

    STEP 3: Add JavaScript for interactivity. Lastly, we will add JavaScript to control the visibility of the modal component. We will set up event listeners on various elements to handle the opening and closing behaviour of the modal component. const modalOverlay = document.getElementById('modal-overlay'); const modalOpen = document.getElementById ...

  14. html Modal popup

    Sampson. 266k 75 544 568. Note: bgiframe is another plugin that's used to circumvent some of IE6's form-rendering issues. - Sampson. Jan 2, 2010 at 17:51. Add a comment. 1. A modal popup that does not disappear on click: var popup = document.getElementById ("popup"); function openPopup () { popup.style.display = "block"; } function closePopup ...

  15. Create a modal from scratch

    New to CSS Grid? Watch the full Crash Course here: https://www.youtube.com/watch?v=yOPCQ5nD1Vs&t=214sIn this video I go over how to create this Welcome Modal...

  16. How to Create a Modal Dialog Box with CSS and JavaScript

    Another advantage that suggests modal dialog is that they decrease load times attracting the users. Now that we learn what is Modal dialog, let's see how we can create them. There are various ways to create modal dialog by using HTML, CSS, and JavaScript. Let's start creating our code step by step!

  17. Interactive Modals with JavaScript

    You can use pure HTML to create modals as opposed to dynamically creating them with JS. I will show you how in the next section. 4. How to Use. In this section, I'll provide examples of how you can use the modal class. 4.1. Autogenerate Modals. The following HTML code will create two new modals and anchor links to open them:

  18. How to Create a Modal Window For Your Websites

    In this video I'll show you how to create a custom modal window for use on your websites using plain HTML, CSS & JavaScript. This is very easy to do and can ...

  19. :modal

    The :modal CSS pseudo-class matches an element that is in a state in which it excludes all interaction with elements outside it until the interaction has been dismissed. Multiple elements can be selected by the :modal pseudo-class at the same time, but only one of them will be active and able to receive input.

  20. 70+ CSS Modal Windows

    70+ CSS Modal Windows. Welcome to our collection of CSS modal windows! In this curated compilation, we have gathered a diverse range of HTML and CSS modal window code examples sourced from reputable platforms such as CodePen, GitHub, and other valuable resources. With our April 2023 update, we are excited to present six new additions to our ...

  21. CTA Modal: How To Build A Web Component

    Constructor #. Whenever a JS class is instantiated, its constructor function is called. That is just a fancy term that means an instance of the CtaModal class is being created. In the case of our Web Component, this instantiation happens automatically whenever a <cta-modal> is encountered in a page's HTML.

  22. 31 abandoned L.A. County dogs in danger of being euthanized

    The kennel has tried to reach out to several shelters in the area that are equipped to take on the dogs, but most don't have the capacity. Redline is emotional about potentially transferring the ...

  23. How To Create Modal Images

    Learn HTML Tutorial Reference Learn CSS ... Learn how to create responsive Modal Images with CSS and JavaScript. Modal Image. A modal is a dialog box/popup window that is displayed on top of the current page. This example use most of the code from the previous example, ...