An example of creating a dialog box in html. HTML Applications: Using Dialog Boxes (Part 1). Styling Dialog Boxes

A modal window that is simple in function, which is completely made in pure CSS, where you can put under different functions to call on the site. This is probably one of many that I have come across from a selection of modal windows, in terms of its settings, but also in terms of installation. But the main thing is its functionality, which will not be inferior to others. Also, by default it is made in a light shade, where in the right top corner There is a button installed in the form of a cross.

Which will be used to disable the function or simply to make the frame disappear, where even on this small element there is an effect of changing the color palette. Now the web master can put it on the site and place in it a description or operators that can display different categories, as statistics or informer.

But the thing is, if you have a dark resource style, then in style you can quickly change the gamma, or rather, adapt it to original design. Here is one of the standard methods how to do it pure CSS to a modal window that will be launched when the button under the link with HTML binding is clicked. The button itself is more for visibility, where in the styles, removing one class will leave the name, which can be placed either in the navigation or in the control panel, where the main functionality or site navigation is located.

This is when checking that everything works fine:

Let's start installation:

Window with a button



ZorNet.Ru - webmaster portal×
Here you will find content on the topic for the site.


CSS

Butksaton-satokavate (
display: inline-block;
text-decoration: none;
margin-right: 7px;
border-radius: 5px;
padding: 7px 9px;
background: #199a36;
color: #fbf7f7 !important;
}

Anelumen (
display: flex;
position: fixed;
left: 0;
top: -100%;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
opacity: 0;
-webkit-transition: top 0s .7s, opacity .7s 0s;
transition: top 0s .7s, opacity .7s 0s;
}

Anelumen:target (
top: 0;
opacity: 1;
-webkit-transition: none;
transition: none;
}

Anelumen figure (
width: 100%;
max-width: 530px;
position: relative;
padding: 1.8em;
opacity: 0;
background-color: white;
-webkit-transition: opacity .7s;
transition: opacity .7s;
}

Anelumen.lowingnuska figure (
background: #f9f5f5;
border-radius: 7px;
padding-top: 8px;
border: 3px solid #aaabad;
}

Anelumen.lowingnuska figure h2 (
margin-top: 0;
padding-bottom: 3px;
border-bottom: 1px solid #dcd7d7;
}

Anelumen:target figure (
opacity: 1;
}

Anelumen.lowingnuska.compatibg-ukastywise (
text-decoration: none;
position: absolute;
right: 8px;
top: 0px;
font-size: 41px;
}

Anelumen.nedismiseg (
left: 0;
top: 0;
width: 100%;
height: 100%;
position: fixed;
background-color: rgba(10, 10, 10, 0.87);
content: "";
cursor: default;
visibility: hidden;
-webkit-transition: all .7s;
transition: all .7s;
}

Anelumen:target .nedismiseg (
visibility: visible;
}


You also need to know that CSS styling and pseudo-class are one of those that are not fully used by CSS features with many interesting potential applications.

It starts when URL address page corresponds to the identifier of its element, or you can say it differently, this is when the user jumps to specific element On the page.

Very often, dialog boxes are used to enter any data in Windows applications. These windows contain controls in which the data required by the application is entered, and OK and Cancel buttons, the first of which confirms the data entry, and the second cancels.

There are two types of dialog boxes:

  • Modal dialog boxes block all other windows of the application, that is, the user will not be able to access any other window until he closes the dialog box by clicking OK or Cancel. Typically, modal dialog boxes are used to enter some data that is critical for the application to continue running. For example, the file open dialog is always made modal.
  • Modeless (modeless) dialog boxes do not block other application windows. The user can freely switch between such a dialog box and any other application window. Modeless dialog boxes are used much less frequently than modal ones. They are used to specify operating parameters that are not critical for the continuation of the program and to perform various actions with the main window or the document loaded in it. Thus, the search dialog is always made modeless.

Internet Explorer allows us to use both modal and modeless dialog boxes in HTML applications. Now we will look at how this is done.

Note:
Before reading this article, it is strongly recommended that you read the previous three articles in the series on Internet Explorer HTML applications.

1. Prepare a test HTML application
Let's create a simple HTML text editor application without any bells and whistles. It will contain a large editing area, where, in fact, the text is entered, and the Parameters button, when clicked, a dialog box for entering parameters will be displayed.

The set of parameters that the user can specify will be small. This is, first of all, the text wrap function in the editing area - whether it will be enabled or disabled. And text color; let the user be able to choose between black, blue, green and red.

We will implement this application in two versions: the first will use a modal dialog box to enter parameters, and the second will use a modeless dialog.

The HTML code for the application is given below.




Text editor


window.resizeTo(710, 490);









Let's save this application in two files: Textedit_modal.hta (version with a modal dialog box) and Textedit_modeless.hta (version with a modeless dialog box). And let's get started...

2. How dialog boxes are implemented
But first, a short theoretical course. First of all, the content of any dialog box - both modal and non-modal - is implemented in the form of a regular web page. This web page is saved in separate file with the htm or html extension (as well as the contents of individual “windows” of the application, the creation of which was described in the second article of the series).

When opening a modal dialog box, we can pass some data to it (more on this later). These could be, say, the current values ​​of application parameters, which will then be substituted into the dialog box controls.

When we close a modal dialog, we can pass some data to the window that opened it. In the case of a settings dialog, these could be user-entered parameter values.

When we open a modeless dialog box, we cannot pass any data to it, and we also cannot return the data entered into it to the window that opened it. However, we can access this window from the window that opened it, and, conversely, “get” from the dialog box to the window that opened it. We can use this to exchange data between windows and perform actions on the contents of one window from another.

That's all for now. Let's get into practice. And we will consider other theoretical issues along the way.

3. Implementation of modals dialog boxes
Let's start by implementing modal dialog boxes as the most commonly used ones.

3.1. Opening a modal dialog box
We just learned that the content of the dialog box is implemented as a regular web page. Creating a web page is not difficult for us. But how do you open the dialog box itself?

To open a modal dialog box, use the showModalDialog method of the Window object. The format for calling this method is:

.showModalDialog(
[,
[,
]]
);
The first parameter of this method is required. It specifies the Internet address of the web page that implements the contents of the dialog box, as a string.

Window.showModalDialog("options_modal.html");
The second parameter is optional. It specifies the value that will be passed to the dialog box. (We'll look at how to get this value in the dialog box later.) The value passed can be any type: string, number, boolean, array, function, or an instance of any object.


Here we have passed the number 2 to the dialog box.

The third, also optional, parameter specifies the parameters of the dialog box itself. It should be a string containing the names of the parameters and their values. The parameter name is separated from the value by a colon, and individual parameters separated from each other by a semicolon (as in the case of writing CSS styles).


"dialogHeight:300px;dialogWidth:400px");
Here we specified the parameters of the dialog box to open - height (300 pixels) and width (400 pixels).

The list of dialog box options supported by Internet Explorer is quite large. Let's look at them.

  • dialogLeft - sets the horizontal coordinate of the top left corner of the dialog box relative to the top left corner of the screen. If this parameter is not specified, the horizontal coordinate of the window will be chosen arbitrarily.
  • dialogTop - sets the vertical coordinate of the top left corner of the dialog box relative to the top left corner of the screen. If this parameter is not specified, the vertical coordinate of the window will be chosen arbitrarily.
  • dialogHeight - sets the height of the dialog box. If this parameter is not specified, the dialog box will have its default height. The minimum possible height value is 100 pixels.
  • dialogWidth - sets the width of the dialog box in pixels. If this parameter is not specified, the dialog box will have the default width. The minimum possible width is 250 pixels. To specify the coordinates of the upper left corner and the dimensions of the dialog box, any unit of measurement supported by CSS can be used, with the obligatory indication of its designation. So, in the example above, the px characters placed after the height and width values ​​indicate that they are specified in pixels.
  • dialogHide - specifies whether the dialog box should be hidden when printing or preview before printing. A value of yes, 1, or on indicates do this, and a value of no, 0, or off indicates not to do this. The default value is no.
  • center - specifies whether the dialog box should be in the center of the screen. A value of yes, 1, or on tells Internet Explorer to center the dialog box on the screen, while a value of no, 0, or off tells Internet Explorer not to do so. The default value is yes.

    Note:
    If you specify the coordinates of the dialog box using the dialogHeight and dialogWidth parameters, the dialog box will be located at the specified location on the screen, regardless of the value of the center parameter. Or, in other words, the dialogHeight and dialogWidth parameters take precedence.

  • edge - sets the type of border that will be displayed around the contents of the dialog box, inside its client area ( client area- this is the inner area of ​​the window where the actual content of the web page is displayed). The raised value indicates to display a “raised” frame (in fact, such a frame is almost invisible), and the sunken value indicates a “recessed” one (and this frame is noticeable quite well and, I must say, greatly spoils the view). The default value is raised.
  • resizable - indicates whether the user will be able to resize the dialog box. A value of yes, 1 or on gives it this ability, but a value of no, 0 or off does not. The default value is no. Almost all dialog boxes used in professionally written applications have a constant and unchangeable size. Make a dialog box with resizable there is no point, in addition, such a window will look strange.
  • scroll - specifies whether the dialog box will have scroll bars. A value of yes, 1, or on tells Internet Explorer to display them, while a value of no, 0, or off causes Internet Explorer not to display them. The default value is yes. It's strange that the Internet Explorer developers decided to give dialog boxes scroll bars by default. In the author's memory, not a single Windows application that came into his hands had dialog boxes with scroll bars (unless, of course, you count student's crafts, in which something similar was encountered...). In general, a scrolling dialog box looks extremely ridiculous. So the conclusion is clear - we remove the scroll bars!

    Window.showModalDialog("options_modal.html", 2,
    "dialogHeight:300px;dialogWidth:400px;scroll:no");

  • status - specifies the presence or absence of a status line in the dialog box. A value of yes, 1 or on displays a status line in the window, while a value of no, 0 or off does not. The default value is no. The status line in the dialog box is clearly an unnecessary accessory. Not a single application with which the author dealt did such things. We won't either.
  • unadorned - specifies whether the dialog box should have a border, title, system menu and buttons to maximize, minimize and close, or, as they say now, chromium. A value of yes, 1 or on specifies the absence of chromium, and a value of no, 0 or off specifies its presence. The default value is no. In general, you should remove chrome only from sophisticated dialog boxes in similarly sophisticated applications. A window without chrome looks extremely unusual and can discourage the user.

After calling the showModalDialog method, web script execution stops until the dialog box is closed. Execution will continue only after the window is closed.

It remains to say about the result that the showModalDialog method returns. This is the value that was passed by the dialog box to the window that opened it. This value can be any type: string, number, boolean, array, function, or an instance of any object.

Note:
Calls to the showModalDialog method can only be present in event handlers that occur as a result of user actions (for example, a click event). Otherwise, the call to this method will be ignored.

3.2. Passing some data to a modal dialog when it opens
Very often you need to pass some data to the modal dialog box that opens. For example, these could be the current values ​​of parameters that should be substituted into the controls of this window.

We already know that we can pass a value of any type to a modal dialog by making it the second parameter to the showModalDialog method call.

Window.showModalDialog("options_modal.html", 2);
But what if we need to pass multiple values ​​to the dialog box? There are two ways to do this.

Method one is to create an array and put the values ​​to be passed into its elements.

Var aParams = true;
var aParams = "black";

Here we have created a regular aParams array with two elements, which have been assigned values ​​that are passed to the dialog box.

We can create and associative array(hash):

Var aParams["wrap"] = true;
var aParams["color"] = "black";
window.showModalDialog("options_modal.html", aParams);
Perhaps this is more convenient - string hash indices are easier to remember than numeric indices of a regular array.

The second method is to create an instance of the Object object using a JavaScript initializer, create properties in it, and assign the passed values ​​to them.

Var oParams = ( wrap: true, color: "black" );
window.showModalDialog("options_modal.html", oParams);
Which method to choose is a matter of taste. For example, the author prefers Object instances, reading them as the most suitable for this purpose. And some may find arrays more convenient - regular ones or hashes.

3.3. Receiving in a modal dialog the data passed by the window that opened it
So, we passed the data to the modal window. Now we need to somehow get them in this window itself.

The Window object supports a read-only dialogArguments property. It stores the value that was passed to the dialog box as the second parameter of the showModalDialog method. Just what we need.

Note:
The dialogArguments property is only available in dialog boxes.

This is how we can get the values ​​passed as hash elements:

Var aParams = window.dialogArguments;
var bWrap = aParams["wrap"];
var sColor = aParams["color"];
And this is the values ​​passed as properties of an instance of the Object object:

Var oParams = window.dialogArguments;
var bWrap = oParams.wrap;
var sColor = oParams.color;
3.4. Passing data from a modal dialog to the window that opened it
It remains to figure out how to transfer data to reverse direction- from a modal dialog box to the window that opened it. We will have to return new user-specified values ​​from the parameters dialog box, right?

Any value should be passed from a dialog box to the window that opened it only if the user clicked the OK button. If you click Cancel, you usually don't need to do this; In general, the Cancel button should only close the dialog box and not perform any other action.

So, the user clicked the OK button in the dialog box. Now we need to pass some data to the window from which the dialog was opened. How to do it?

The Window object supports a returnValue property. This property stores the value that should be passed from the modal dialog to the window that opened it. This value can be of any type.

Note:
The returnValue property is only available in modal dialog boxes.

For example, this is how we can pass a single value from the window that opens:

Window.returnValue = 2;
And so - several meanings:

Window.returnValue = ( wrap: bWrap, color: sColor );
Of course, in this case we can also use a regular array or hash.

If the user clicked the Cancel button in the dialog box, we, as agreed earlier, will not assign any value to the returnValue property. In this case, this property will receive its default value - null. By the way, the same thing will happen if the user closes the dialog box by pressing the close button or the + key combination.

Fine! The dialog box is closed (we will find out how to close it later). Now the window that opened it should receive the value of the returnValue property. How?

Very simple. The returnValue property value will be returned by the showModalDialog method as a result. However, this was already mentioned in paragraph 2.1.

We have to check if this value is null. If so, then the dialog box did not transmit any data. Otherwise, we will be able to somehow use the data passed to them in the application.

Var oResult = window.showModalDialog(...);
if (oResult != null) (
var bResultWrap = oResult.wrap;
var sResultColor = oResult.color;
}
3.5. Closing a modal dialog
Finally, we should actually close the modal dialog box. To do this, we can use a method that does not accept parameters and does not return a result. close object Window.

Window.close();
3.6. HTML application with support for modal dialogs
Well, it's time for pure practice. Let's complete our HTML text editor application so that it supports setting parameters using a modal dialog box.

The code of the HTML application itself (the Textedit_modal.hta file) after the corrections will look like this:




Text editor


window.resizeTo(710, 490);

Var bWrap = true;
var sColor = "black";

Function showParameters()
{
var oParams = ( wrap: bWrap, color: sColor );
var oResult = window.showModalDialog("options_modal.html", oParams,
"dialogHeight:120px;dialogWidth:200px;scroll:no");
if (oResult != null) (
bWrap = oResult.wrap;
sColor = oResult.color;
var oTxtText = document.getElementById("txtText");
oTxtText.wrap = bWrap ? "soft" : "off";
oTxtText.style.color = sColor;
}
}










Here, in principle, everything is already familiar to us. Only minimal explanation is required.

First of all, we declared two variables - bWrap and sColor - that will store the current values ​​of the application parameters. The first variable will store a logical value - an indication of whether the editing area is being executed in this moment line wrapping. And the second variable will store the current value of the text color in the edit area as a string.

Note:
In general, the current values ​​of the parameters can not be stored anywhere at all, but each time obtained from the corresponding properties of the instance of the HTMLTextAreaElement object, which represents the editing area where the text is entered. The author simply decided not to overcomplicate the application code.

An edit area is represented by an instance of an HTMLTextAreaElement object. This object supports the wrap property, which specifies the line wrapping mode. The value "soft" of this property instructs the editing area to perform line breaks, and carriage returns and line feeds will not be inserted at the breaks ("soft" line breaks). And the value "off" tells the editing area not to break lines at all.

All objects representing web page elements support style property. This property stores an instance of the CSSStyle object representing the current CSS style, which is bound to a given web page element.

The CSSStyle object, in turn, supports many properties corresponding to various style attributes. Thus, the color property corresponds to the style attribute of the same name, which specifies the color of the text.

Now let's create a web page that implements the dialog box itself. Let's place on it the Wrap text checkbox, the Text color drop-down list and, of course, the OK and Cancel buttons that are required for windows of this type.

The code for this web page is given below.




Options

function setup()
{
var oParams = window.dialogArguments;

OChkWrap.checked = oParams.wrap;
oSelColor.value = oParams.color;
}

Function sendParams()
{
var oChkWrap = document.getElementById("chkWrap");
var oSelColor = document.getElementById("selColor");
window.returnValue = ( wrap: oChkWrap.checked, color: oSelColor.value );
window.close();
}




Wrap text


Text color

Black
Red
Green
Blue








Here, again, everything is already familiar to us. The most minimal explanations are required.

The SIZE attribute of the tag that creates the list specifies the size this list in points. A value of 1 for this tag attribute specifies that the list should be one item high, that is, it should be a drop-down list.

The VALUE attribute of a tag that creates a separate list item specifies the value of that item.

Immediately after the web page that implements the dialog box finishes loading, the load event will occur. We specified the setup function as a handler for this event. This function will receive the value passed to the dialog box from the window that opened it - an instance of an Object with properties that store the current values ​​of the application's settings. After that, it will enter these values ​​into the corresponding controls.

The HTMLInputElement object, which represents a control, including a checkbox, supports a checked property, which is available only for checkboxes. This property indicates whether the checkbox is checked (true) or cleared (false).

The HTMLSelectElement object, which represents a list, supports a value property. It contains the value of the currently selected list item as a string. By assigning a value to this property, we will tell the list to initially select an item with that value.

When you click on the OK button, the handler for its click event will be executed - the sendParams function. It will create an instance of an Object using a JavaScript initializer, and set its properties to the values ​​that the user specified in the dialog box controls - these will become the new values ​​of the application parameters. It will pass the resulting instance of the object to the window that opened this dialog box, that is, to the application itself, and then close the dialog box.

The Cancel button simply closes the dialog box. As a result, the window that opened this dialog box will receive the value null - a signal that the user did not confirm the entry of new application parameters.

Let's save this web page in the file options_modal.html. And let's check the finished HTML application in action.

The HTML5 dialog element provides functionality in a dialog box on a web page. The dialog element's dialog box resides in the DOM tree, and can be styled using regular CSS.

Simple examples of the dialog element Dialog window! The dialog element itself will not visually show anything; you need to use the JavaScript API to open and close the dialog box. .show() and .close() API Using the .show() and .close() APIs on the dialog DOM element, you can open and close a dialog box.

Dialogue window!

Close Open Dialog! var dialog = document.querySelector("dialog"); document.querySelector("#show").onclick = function() ( dialog.show(); ); document.querySelector("#close").onclick = function() ( dialog.close(); );

Dialogue window!

Close Open dialog box!

Style for a dialog box You can add a custom style to the dialog element in the same way as to other block elements: nav, div, footer, etc.

dialog ( border: 1px solid rgba(0, 0, 0, 0.3); border-radius: 6px; box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); )

Styling a dialog element is just as easy as styling a div!

Close Open styles dialog

Function.showModal() API To make a dialog box modal, you need to call the .showModal() function instead of .show() . Please note that you cannot select text in background

or click the button to select buttons in the open dialog box.

Document.querySelector("#show").onclick = function() ( dialog.showModal(); );

This layer is on top of other element windows, regardless of z-index values, including previously opened modal dialog boxes.

If necessary, you can close the modal dialog using the “escape” key!

Close

Add a background to a dialog box

To fill the background with color, you can use the pseudo-element::backdrop .

Dialog::backdrop ( position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.8); )

Dim background using ::backdrop . It highlights the dialog box while hiding the rest!

Close Open dialog box with background

Returning values ​​from a dialog box You can pass an argument to .close() . The dialog returns set value

properties.returnValue .

Open a dialogue!

The dialog box receives a close() argument. This will be reflected in .returnValue

Send Open dialog Advantages of the element Of course, you can use jQuery library or other JavaScript to get this result. But dialog is HTML element and you don’t need to connect third-party libraries to create a pop-up dialog box.

The element is also great for accessibility. The browser understands that the element is modal, so technologies such as screen readers know what content should be interactive.

Additionally, modal dialogs are placed quite orderly in a "top layer" stack, and sit on top of other elements, regardless of z-index properties. Relying on z-index, placing a modal dialog on top of web pages is difficult.

Position

Dialogues have some special positioning characteristics. By default, when you call dialog.show(), the dialog box is centered in the viewport. Of course you can change this using regular CSS positioning like top: 15px .

And you also need to know that absolute positioning dialog box, only for the block containing the initial container. Therefore, an absolute positioned dialog doesn't understand things like position, overflow, and percentages.

The spec includes a positioning anchor that allows you to anchor the dialog to another element. However, this is not yet implemented in Chrome.

Open multiple dialog windows

If dialogs are not modal, they behave like multiple elements. For modals, the browser pushes the dialog onto the stack. The top of the stack is an active modal dialog box that blocks the remaining pages of the document. Whenever a modal dialog is opened, it is pushed to the top of the stack. Whenever a modal dialog is closed, it is removed from the stack. Dialogs are displayed in stack order, so the active dialog is the highest.

New HTML5 elements and new JavaScript APIs allow us to create complex applications for browsers. Part of any modern application are various dialog boxes. They prompt users to confirm certain actions or simply display messages. With a new element "" Now we can create these windows using pure HTML5.

Simple markup without styles

The element can be placed anywhere inside body tag on the HTML page. It is not recommended to place it in text paragraphs -

, as this may cause display problems. This is most likely to happen with elements that contain additional elements and not only text ones. Property definition " open" will show a dialog box when the page is opened. Without this property, the window will be in original form closed.

Please read our Terms of Service.

Terms of Service …

In our example, we defined a dialog box between two paragraphs. This position of the element ensures that it is shown horizontally and centered, without taking into account the flow of other elements. Vertically, it calculates its position relative to the top border of the browser window. If you're happy with this, then no CSS is required.

If the standard view isn't for you, add your own styles and customize it to your liking. You can use any CSS properties how to customize block elements - most used "border-radius" And "shadow" for additional effects.

Managing Dialog with JavaScript

To open and close an element use JavaScript methods show() And close().

document.getElementsByTagName ("span" ) [ 0 ] .addEventListener ( "click" , function () (
document.getElementsByTagName("dialog")[0].show();
) , false ) ;

Document.getElementsByTagName ("dialog" ) [ 0 ] .addEventListener ( "click" , function () (
this.close();
) , false ) ;

In our example, we define two events. The first event causes a dialog element to open when the first element is clicked . Clicking on an open dialog box will close it.

Shapes inside Dialog element

The element can contain not only simple text, but also additional elements. This allows us, for example, to place a form inside a dialog box. Please note that instead of conventional methods "post" And "get" you will need to use a special method" dialog" to process the form content.


Our Terms of Service...

Accept
Refuse

In this example, we created a form with two buttons inside a dialog. Clicking any of the buttons closes the dialog element. No JavaScript required here. But if you want to prevent the window from closing on click, you still need to use JavaScript. Just add the event " click" for a button, which will prevent the default button action with "preventDefault()".

Reaction to closing a dialog box

Event "close" allows us to respond to the dialog box being closed.

document.getElementsByTagName ("dialog" ) [ 0 ] .addEventListener ( "close" , function (e) (
var answer = this .returnValue ;
) , false ) ;

Property "returnValue" returns "value"- the value of the button that was used to close the window. If in our example the "Refuse" button was clicked "ReturnValue" will return the value "no" (value="no"). Это дает нам простой способ инициирования определенных функций в зависимости от нажатой кнопки.!}

Creating a Modal Dialog Box

If you want to make sure that no other content on your HTML page can be accessed while the dialog is open, then you can use modal dialogs. They will only open when JavaScript help and his method" showModal()"Modal dialogs make all other content inactive. You cannot click, change, or select inactive content.

document.getElementsByTagName("dialog")[0].showModal();

Unlike standard dialog boxes, the modal option will be centered not only horizontally, but also vertically.

If you want to use a different color you can use the pseudo-element " ::backdrop"Make sure you choose a color with a low value" RGBA()" to avoid complete concealment of the content.

dialog: :backdrop (
background : rgba(255 , 0 , 255 , 0.25 ) ;
}

In our example, we decided to use a light yellow color. If you want you can choose background image instead of color.

Modal dialogs can always be closed by pressing the ESC key. This makes it necessary to add another event to the dialog. As soon as the event "close" worked when the window is closed using a form button, make sure you add an event "cancel". It will fire as soon as the modal window is closed using the ESC key.

document.getElementsByTagName ("dialog" ) [ 0 ] .addEventListener ( "cancel" , function (e) (
var answer = "cancelled" ;
) , false ) ;

Using more than one Dialog element on a page

If you have more than one open dialogue at the same time, use styles to make sure they don't overlap. Exception for modal windows, they will always block other content and thus will not allow the use of more than one modal window simultaneously.

Browser support

Support for the element is not yet widespread enough at the time of this writing. Only Chrome And Safari interpret the element correctly. All other browsers treat it as simple block element, which means they will always show its contents regardless of whether the property is set "open" or not. The current state of affairs is possible.


If you have any questions, we recommend using our

After a huge number of pop-up advertisements on various sites, the attitude towards various dialog boxes is somewhat negative. However, everything certainly depends on the purpose for which they are used. Sometimes their use is necessary and greatly simplifies the user experience.

Previously, to create dialog boxes you needed to connect jQuery plugin like Pop Easy, Twitter Bootstrap Modal or jQuery UI Dialog. However, HTML 5, which has grown significantly in capabilities, allows you to avoid using them by using a built-in element called .

Previously, back in 2009, this element was already part of HTML 5, but was excluded from it. Now he is back again - in a new form.

Element support by browsers

Unfortunately, its support is extremely limited at the moment. It can only be used in Safari 6.0 and Chrome Canary. However, in Chrome Canary you need to first activate it in the settings. To do this, go to chrome://flags and enable “Enable experimental Web Platform features”.

Interacting with HTMLDialogElement Methods:

HTMLDialogElement has the following methods that allow you to work with dialog boxes.

  • show() : This method is used to open a dialog. The difference between this method and the next one is that despite the open dialog window, users still have the opportunity to use the page - they can scroll it, copy something, follow links without reloading the page, etc.
  • showModal() : In in this case The user only has access to the open “modal window”.
  • close() : This method closes the dialog. Looking ahead a little, I’ll say that you can pass the returnValue parameter in it.
Attributes:

HTMLDialogElement includes the following two attributes.

  • returnValue: Returns the parameter that was passed to close() - it is not necessary to specify it, it is optional.
  • open: Is a Boolean data type. Which means that it can only take two values ​​- true, in which case the dialog will be shown to the user, or false, then it is hidden.
Events:

The function called when closing the onk looks like this:

dialog.addEventListener("close", function() ( Here you can already write code to be executed if the window is closed ));

In addition to the above mentioned methods and attributes, it also supports:

  • form: Used to integrate a form with . Thanks to this binding, it works only inside the dialog box.
  • autofocus attribute: Needed to focus on inputs inside the dialog.
  • cancel event: This event will be triggered after the window is closed via a key “Esc.”

Now, having studied the basics, you can see a practical example of its use.

Syntax for creating dialog boxes

Thanks to Hevix for a great lesson;)

Close Open window

The code is so clear and simple that I think it requires no explanation. What you need to understand is that the content of the popup window is inside the tag, and its call should be outside this tag.

To display the element's contents you need using JavaScript, namely calling the .show() and .close() methods. They have already been mentioned earlier.

(function() ( var dialog = document.getElementById("Dialog"); document.getElementById("showDialog").onclick = function() ( dialog.show(); ); document.getElementById("closeDialog").onclick = function() ( dialog.close(); ))();

(function() (

document. getElementById("showDialog"). onclick = function () (

dialog. show();

document. getElementById("closeDialog"). onclick = function () (

dialog. close();

} ) () ;

All is ready. As you can see, we used a minimal number of lines of code, which is incommensurate with what if we connected a third-party plugin for this. Now, when you click on the “Open Window” button, you will see a dialog box; clicking on the “Close” button will hide it.

Styling Dialog Boxes

I don't think there's a need to delve too deeply into how to style this pop-up window with using CSS. Everything is very clear here even without my help. I'll just ask him general style for the layout.

dialog ( top: 28%; width: 400px; border: 1px solid rgba(0, 0, 0, 0.3); border-radius: 15px; box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); border-top: 5px solid #eb9816; ) button( display: inline-block; border-radius: 3px; border: none; font-size: 0.9rem; padding: 0.4rem 0.8em; background: #eb9816; border-bottom : 1px solid #f1b75c; font-weight: bold; margin: 0 0.25rem; button:hover, button:focus ( opacity: 0.92; cursor: pointer; )

dialog (

top: 28%;

width: 400px;

border : 1px solid rgba (0, 0, 0, 0.3 ) ;

border-radius: 15px;

box-shadow : 0 3px 7px rgba (0, 0, 0, 0.3 ) ;

border-top : 5px solid #eb9816 ;

button(

display: inline-block;

border-radius: 3px;

border: none;

font-size: 0.9rem;

padding: 0.4rem 0.8em;

background : #eb9816 ;

border-bottom : 1px solid #f1b75c ;

color : white ;

font-weight: bold;

margin : 0 0.25rem ;

text-align: center;

button:hover, button:focus (

opacity: 0.92;

cursor: pointer;

Creating Modal Dialog Boxes

If you want to focus the user's full attention on the pop-up window, it makes sense to use modal dialog boxes. Their challenge is not much different from the usual ones. You only need to change in the JS file .show() to the .showModal() . You don't need to change anything in the HTML.

(function() ( var dialog = document.getElementById("Dialog"); document.getElementById("showDialog").onclick = function() ( dialog. showModal(); ); document.getElementById("closeDialog").onclick = function() ( dialog.close(); ))();

(function() (

var dialog = document. getElementById("Dialog");