DEV Community

Cover image for Create a modal without JavaScript!
Faiz Byputra
Faiz Byputra

Posted on

Create a modal without JavaScript!

Hi there! Recently I found out that HTML has a tag named dialog. So what is it and how to use it? Let's find out together and make a modal with it!

<dialog> is an HTML tag that represents dialog box which can be used for many thing such as alert, subwindow, or a modal. Commonly, people use JavaScript to make an interactive element that manipulate the actual DOM. But now HTML has a tag so that you can make a modal easily! So let's get into it.

Make the modal window

First, you need to declare the <dialog> tag with an id that will be used to target it when we want to open it with a button.

<dialog id="modal">
  <h1>Welcome!</h1>
  <p>Click Close or press esc to close modal</p>
  <form method="dialog">
    <button>Close</button>
  </form>
</dialog>
Enter fullscreen mode Exit fullscreen mode

Anything inside the <dialog> tag will be shown in the dialog box. Here we have an <h1>, a <p> tag, and a <form> tag with a <button> wrapped inside.

A form with dialog method is used to close the modal when the button inside it is clicked. Same as any other method, a default type of a button is submit so it will trigger the modal to close.

Make a button to show the modal

At this moment, you will not see anything on your window. It's because the dialog box (modal) is closed or not visible by default. Now we'll make a button to open it.

<button onclick="modal.show()">Show Modal</button>
Enter fullscreen mode Exit fullscreen mode

Notice there's an onclick attribute with value of modal.show(). This means it will target an id of modal and runs a show() function.

Even we didn't write any JS, but the show() function is still a JavaScript function

Dialog box with the button

Congratulations! we just built our own modal without writing any script. Now if you click the button you will see the modal a.k.a. the dialog box on your window.

Styling it with Bootstrap

The modal that we made earlier is pretty boring. So we'll style it using Bootstrap 5.3.

Here's the final code below:

<html data-bs-theme="dark">
  <head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
  </head>
  <body class="m-4">
      <dialog id="modal" class="rounded">
        <h1>Welcome!</h1>
        <p>Click Close or press esc to close modal</p>
        <form method="dialog" class="text-end">
          <button class="btn btn-primary">Close</button>
        </form>
      </dialog>

      <button onclick="modal.show()" class="btn btn-primary">Show Modal</button>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Styled dialog box

Above is the final output of the modal. You can check it live on my Codepen here.

Thank you very much 😁


References:

Top comments (0)