2

How to Build Modals Easily With the HTML Dialog Element

 1 year ago
source link: https://www.makeuseof.com/build-modals-easily-with-the-html-dialog-element/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Build Modals Easily With the HTML Dialog Element

Published 11 hours ago

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

HTML code inside a text editor

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:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dialog demo</title>
</head>

<style></style>

<body></body>

<script></script>
</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:

<div class="button-container">
<button>
Delete item
</button>
</div>
<dialog>
<div>
Are you sure you want to delete this item?
</div>
<div>
<button class="close">
Yes
</button>

<button class="close">
No
</button>
</div>
</dialog>

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:

const modal = document.querySelector("dialog")
document.querySelector(".button-container button").addEventListener("click", () => {
modal.showModal();
});
const closeBtns = document.getElementsByClassName("close");
for (btn of closeBtns) {
btn.addEventListener("click", () => {
modal.close();
})
}

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:

document.querySelector(".button-container button").addEventListener("click", () => { modal.show(); });

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:

dialog::backdrop {
background: black;
opacity: 0.5;
}
button {
border-radius: 2px;
background-color: white;
border: 1px solid black;
margin: 5px;
box-shadow: 1px 1px 2px grey;
}
dialog {
max-width: 90vw;
border: 1px solid black;
}

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK