Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

The `<dialog>` Element – Native Modal D | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 43 of 55

·HTML

The `<dialog>` Element – Native Modal Dialogs

9 min

Course progress78%

What you'll learn

Keep these ideas in mind as you work through the lesson.

5 points
  • Native modal behavior using the `<dialog>` element
  • Methods `showModal()` and `close()` and their effects
  • Automatic focus management and Escape‑key handling
  • Using `returnValue` to communicate the dialog result
  • Polyfill options for browsers that don’t support `<dialog>`

The <dialog> Element – Native Modal Dialogs

HTML5 introduced <dialog> for creating accessible modal windows without JavaScript polyfills.

<dialog id='myDialog'>
  <h2>Subscribe</h2>
  <form method='dialog'>
    <label for='email'>Email:</label>
    <input type='email' id='email' required />
    <menu>
      <button type='submit'>Send</button>
      <button type='reset'>Cancel</button>
    </menu>
  </form>
</dialog>

<button id='openBtn'>Open Dialog</button>
<script>
  const dialog = document.getElementById('myDialog');
  document.getElementById('openBtn').addEventListener('click', () => dialog.showModal());
  dialog.addEventListener('close', () => console.log('Dialog closed with value:', dialog.returnValue));
</script>

Built‑in features

  • Focus trapping – Browser keeps focus inside the dialog while it’s open.
  • aria-modal – Implicit when using showModal(); screen readers recognise the modal state.
  • Keyboard support – Esc automatically closes the dialog.
  • returnValue – Allows the form to pass back a value when the dialog is closed.

Polyfill for older browsers

If you need to support browsers that lack <dialog>, include a small polyfill (e.g., dialog-polyfill.js). The polyfill mimics the API and provides similar accessibility features.


Quick checklist for <dialog>

  1. Dialog opened with showModal() (modal) or show() (modeless)? ✅
  2. Focus trapped inside the dialog? ✅
  3. Escape key closes the dialog? ✅
  4. Polyfill added for unsupported browsers? ✅
  5. Dialog properly labelled (<h2> or aria-label)? ✅

Tip: Use the open attribute (<dialog open>) during development to see the dialog without JavaScript.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
Previous lessonThe `<picture>` Element and Responsive ImagesContinue to lesson 44The `<template>` Element – Declaring Inert Template ContentBack to HTML Course curriculum