DEV Community

Cover image for How to create modals in html (easy way)
Omar Jabraoui
Omar Jabraoui

Posted on

How to create modals in html (easy way)

Modals are those components that can be opened following an event, usually the click of a button but not only.

Image description

They are easy to recognize because usually when you open one, a small popup with HTML code inside is shown, usually a form to fill out, and its background becomes darker to stand out from the rest of the page.

They are important precisely because they can focus the user's attention on that particular thing and make sure that as long as they have not completed the action or closed the modal of their own free will, the rest of the page remains blocked and it is thanks to the backdrop that it creates.

If you are web developers or people in this field for a long time, you will know that modals, no matter how simple they may seem, have always been a mess to create and make work, so much so that many resorted to bootstrap or other libraries for this.

Today there will no longer be a need for this, there is a particular HTML element that can be used as a modal and more, and it greatly facilitates our work.

In this short and simple guide, you will discover how to use it and finally be able to use it in your future projects.


Modal

  1. Create the element and assign it an Id to make it unique

    <dialog id="signInModal">
        ... Content Here
    </dialog>
    
    
  2. Add the button to close it (the X)

    <div class="flex flex-row items-center justify-between mb-8">
        <h4 class="text-2xl font-semibold">Sign In</h4>
        <button class="closeBtn">&times;</button>
    </div>
    
    

    Give the button a class that we will use later so that all elements with that class can close their own modal.

    This is because usually in modals there is a form and in the form there is also the cancel button, so we want to give the functionality to the "cancel" button to close its own modal, and the best way to do it is through a class and with a couple of lines in javascript that we will see later.

  3. Proceed with the content that your modal will have

    <dialog  class="border border-slate-200 rounded-md w-[45vw] max-w-[340px]" id="signInModal">
            <div class="flex flex-row items-center justify-between mb-8">
                <h4 class="text-2xl font-semibold">Sign In</h4>
                <button class="closeBtn">&times;</button>
            </div>
            <div class="grid grid-cols-1 mb-8 gap-4">
                <div class="flex flex-col gap-1">
                    <label>Name</label>
                    <input type="text" placeholder="Peter" class="border border-slate-200 rounded-md p-2"/>
                </div>
                <div class="flex flex-col gap-1">
                    <label>Email</label>
                    <input type="email" placeholder="peter@gmail.com" class="border border-slate-200 rounded-md p-2"/>
                </div>
            </div>
    </dialog>
    
    
  4. Add the buttons to complete the action (Submit) and to cancel it

    <dialog  class="border border-slate-200 rounded-md w-[45vw] max-w-[340px]" id="signInModal">
        ...content
            <div class="flex flex-row items-center justify-between w-full">
            <button class="p-2 rounded-md w-full text-center closeBtn">Cancel</button>
            <button class="p-2 rounded-md bg-black text-white w-full text-center">Sign In</button>
        </div>
    </dialog>
    
    

    If you have a form inside your modal, I recommend using the correct inputs like type="submit", but for this simple tutorial, I decided to use only buttons.

    The button that will cancel and consequently close the modal, must have the same class we talked about in the second step. In my case it is "closeBtn".

  5. Javascript element

    const modal = document.querySelector('#signInModal');
    
    

    Do you remember the ID we assigned to the modal before? Here it is, we need it to be able to access the dom element from javascript and be able to open and close it at will.

Button

  1. Button creation

    <button class="font-semibold bg-blue-500 text-white p-2 rounded-md" id="openModalBtn" title="Open Modal">Open Modal</button>
    
    

    To open it we will need an event that will start when this button is clicked.
    You can use anything you want, you can even make it open by itself or open by clicking on something else, the logic doesn't change.

    In my case, I gave an id to the button so I can access it from javascript.

    const openModal = document.querySelector('#openModalBtn');
    
    
  2. Click event association

    openModal.addEventListener('click', () => {
      modal.showModal()
    })
    
    

    There are two ways to open the modal:

- showModal(): it will open it just like a modal and it will give it that darker background to detach itself from the rest of the page
- show(): it will open it like an alert, like a normal element at the top of the page. it will still be above all other elements but will not have the same characteristics of a modal like the background etc.
Enter fullscreen mode Exit fullscreen mode

Close modals in a dynamic way

Usually on a webpage, you may have more than one modal and when they become too many, managing them becomes a bit complicated and I'm sure no one wants to create a variable in javascript for every button that closes and for every cancel button for every modal.

That's why we created that class before ".closeBtn" (which you can call whatever you want).

From javascript we can select all the elements that have that class and give them a click event and make them close their own modal.

document.querySelectorAll('.closeBtn').forEach(btn => {
  btn.addEventListener('click', (e) => {
      const closest = e.target.closest('dialog');
      document.querySelector(`#${closest.id}`).close()
  })
})

Enter fullscreen mode Exit fullscreen mode

We are iterating through all the elements with the closeBtn class and we are adding an event to them, that is, when clicked, we take the closest dialog, where the clicked element resides and take the id and with that we can go back to the particular modal and we can close it.

Top comments (4)

Collapse
 
j471n profile image
Jatin Sharma

You can use code highlight by using the following syntax:

Image description

which will have the following output:

const name = "John";
Enter fullscreen mode Exit fullscreen mode

Also it would be better to add some kind of codepen or something else where people can play around.

Collapse
 
omarjab profile image
Omar Jabraoui

thank you, it was my first article. i will make sure to include a codepen link and also format the code correctly from the next one

Collapse
 
j471n profile image
Jatin Sharma

Great. All the best for your future articles.

Collapse
 
adetutu777 profile image
Adetutu Gbangbola

Waow, will definitely try this out. Thanks for sharing