The HTML DOM Dialog object is associated with the HTML5 <dialog> element. It is used for creating popups, modals, etc on the web page. To view the dialog box and let the user interact with it the open attribute value should be set.
Properties
Following are the properties for the Dialog object −
Property | Description |
---|---|
open | To set or return if the dialog should be opened or not. |
returnValue | To set or return the return value of the dialog. |
Methods
Following are the methods for the Dialog object −
Method | Description |
---|---|
close() | To close the dialog. |
show() | To show the dialog. |
showModal() | To make the top most dialog box and display it. |
Syntax
Following is the syntax for −
Creating a dialog object −
var p = document.createElement("DIALOG");
Example
Let us look at an example for the HTML DOM dialog object −
<!DOCTYPE html> <html> <head> <title>DIALOG OBJECT</title> <style> dialog{ border:2px solid blue; font-weight:bold; } </style> </head> <body> <p> Clicking on the button below will create a dialog element</p> <button onclick="createDialog()">CREATE</button> <script> function createDialog() { var dlg = document.createElement("DIALOG"); var dlgTxt = document.createTextNode("DIALOG WINDOW with a button"); var bl=document.createElement("BR"); var btn = document.createElement("BUTTON"); var btnText=document.createTextNode("CLICK HERE"); dlg.setAttribute("open", "open"); dlg.appendChild(dlgTxt); dlg.appendChild(bl); btn.appendChild(btnText); dlg.appendChild(btn); document.body.appendChild(dlg); } </script> </body> </html>
Output
This will produce the following output −
On clicking the CREATE button −
In the above example −
We have first created a button CREATE that will execute the createDialog() function when clicked by the user −
<button onclick="createDialog()">CREATE</button>
The createDialog() function creates the <dialog> element using the createElement() method. It then adds some text to it using the createTextNode() method. We then create a button inside the <dialog> element using the createElement() method and adds the button text using the createTextNode() method.
Using the setAttribute() method we set the open attribute value of the dialog box to display to the user. Finally the dialog box along with the button inside it are appended to the document body using the document.body appendChild() method and passing the <dialog> and <button> element as parameters −
function createDialog() { var dlg = document.createElement("DIALOG"); var dlgTxt = document.createTextNode("DIALOG WINDOW with a button"); var bl=document.createElement("BR"); var btn = document.createElement("BUTTON"); var btnText=document.createTextNode("CLICK HERE"); dlg.setAttribute("open", "open"); dlg.appendChild(dlgTxt); dlg.appendChild(bl); btn.appendChild(btnText); dlg.appendChild(btn); document.body.appendChild(dlg); }