DEV Community

Cover image for How to create super simple Dialogs in HTML
Liftoff Studios
Liftoff Studios

Posted on

How to create super simple Dialogs in HTML

Hello everyone and welcome to this short and simple tutorial.

We all want to add modals in the easiest possible way. While exploring MDN I found the perfect element I hadn't noticed before !!

Dialog Syntax

Pretty easy if you ask me 0.o

<dialog>
    <!--Dialog Content-->
    <div>Hello World !!!!!!!</div>
</dialog>
Enter fullscreen mode Exit fullscreen mode

Wait but this doesn't do anything ?

Yes this doesn't do anything yet
In the dialog element, the dialog doesn't show until an open attribute is present on it.

This should work --->

<dialog>
    <!--Dialog Content-->
    <div>Hello World !!!!!!!</div>
</dialog>
Enter fullscreen mode Exit fullscreen mode

Output

Output of code

So the open attribute is very important. This element can also be automated with JavaScript.

<!--HTML section-->
<button onclick="openDialog()">Open Dialog</button>

<dialog id="dialog">
    <div>Wow this is awesome !!!!!</div>
    <button onclick="closeDialog()">Close</button>
</dialog>


<!--JavaScript-->
<script>
    //Opens Dialog
    function openDialog(){
        document.getElementById("dialog").show();
    }

    //Closes Dialog
    function closeDialog(){
        document.getElementById("dialog").close();
    }
</script>
Enter fullscreen mode Exit fullscreen mode

In this the function opens the dialog with the show method and closes it with the close method.

It is a very simple method to use !!

Take a look at the pen.

Thank You For Reading Through This Short Tutorial

Do remember to like, share and follow me

Top comments (2)

Collapse
 
curiousdev profile image
CuriousDev

Thanks, but is there more to know about the usage of dialogs? It looks like, there should be more than just being able to hide and show these.

Collapse
 
liftoffstudios profile image
Liftoff Studios

It is a dialog, so the basic and most important functions are to open and close. You can put anything inside a dialog and it will appear when you open the dialog