HTML <dialog> Tag: Create a Modal Dialog

<dialog id="dialog1">
<p>Only buy stocks that go up.</p>
<button id="hide">Close</button>
</dialog>
<!-- "Show" button -->
<button id="show">Display Stock Tip</button>

<!-- JavaScript to provide the "Show/Close" functionality -->
<script type="text/JavaScript">
(function() {  
    var dialog1 = document.getElementById('dialog1');  
    document.getElementById('show').onclick = function() {  
        dialog1.showModal();  
    };  
    document.getElementById('hide').onclick = function() {  
        dialog1.close();  
    };  
})(); 
</script>

Only buy stocks that go up.

The above example demonstrates how to create a modal dialog using the <dialog> element.

The only difference between modal dialogs and normal ones (from a coding perspective) is that you use showModal() instead of show() in your JavaScript.

The difference from a user's perspective is that, modal dialogs create a mode where the main window can't be used until the user has interacted with the dialog (i.e. closed it). Most browsers tint the background color to a darker shade, which draws attention to the dialog box.

Here's an example of a normal dialog (i.e. "non-modal").

About the <dialog> Element

The <dialog> element represents a part of an application that a user interacts with to perform a task, for example a dialog box, inspector, or window. Generally, JavaScript is needed in order to make the dialog interactive.

The above example shows how JavaScript can be used to allow the user to show and hide the <dialog> at the click of a button, and specifically, make the dialog modal.

You can (optionally) use the open attribute to display the dialog automatically upon page load.