mles
mles

Reputation: 3456

Pure javascript modal does not show

I'm trying to use this Codepen on my project. I've copied the html, css, javascript:

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            var dialog = document.getElementById('window');
            document.getElementById('show').onclick = function() {
                dialog.show();
            };
            document.getElementById('exit').onclick = function() {
                dialog.close();
            };
        </script>
        <style>
            dialog {
                width: 500px;
                background:black;
                border: 1px solid #dadada;
                font-family:sans-serif;
                padding: 5px 10px 20px 20px;
            }
        </style>
    </head>
    <body>
        <dialog id="window">
            <h3>Sample Dialog!</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum, inventore!</p>
            <button id="exit">Close Dialog</button>
        </dialog>
        <button id="show">Show Dialog</button>
    </body>
</html>

Unfortunately when I click on the "Show Dialog" button nothing happens.

Upvotes: 1

Views: 343

Answers (1)

leo.fcx
leo.fcx

Reputation: 6457

You need to wrap your javascript code in window.onload to make sure DOM is ready before manipulating it as follows:

window.onload = function(){
    var dialog = document.getElementById('window');
    document.getElementById('show').onclick = function() {
        dialog.show();
    };
    document.getElementById('exit').onclick = function() {
        dialog.close();
    };
};

Upvotes: 2

Related Questions