Adding a close icon for an HTML dialog

After publishing the short intro to the dialog element I've received an email asking how can we add a close icon to that icon.

I've made the below example to show how can we do this:
Adding a close icon for an HTML dialog

There are two ways to close an HTML dialog:

  1. programmatically, using the close() method of the dialog element
  2. using a submit button, without any extra Javascript. When a user submits the dialog form, the data is maintained. While there is a submit event it will go through constraint validation and therefore the user data is neither cleared nor submitted.

The code will look like this:

<dialog id="my-dialog">
    <form method="dialog">
        <button type="submit" autofocus>❌</button>
        <p>This modal can be closed using both the <code>close()</code> method or using a <code>submit</code> button.</p>
        <a href="#">Close modal using Javascript</a>
    </form>
</dialog>
<button data-modal>Open the dialog</button>

<script>
    let btnShowModal = document.querySelector('[data-modal]')
    let modal = document.querySelector('#my-dialog')
    btnShowModal.addEventListener('click', () => modal.showModal())
</script>

You can play with the live example here and the full code is on my github.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X