Skip to content
Advertisement

Why doesn’t this code display the button after I hide it?

When I run this JavaScript code, button2 doesn’t get displayed again. I’m not sure why this is happening. I am trying to use this in a game I am creating. I searched this up on Google multiple times and couldn’t find an answer.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style type="text/css">
            .btn1 {
                background-color: white;
                border: 2px solid black;
                border-radius: 12px;
            }
            .btn2 {
                background-color: white;
                border: 2px solid black;
                border-radius: 12px;
                display: none;
            }
        </style>
    </head>
    <body>
        <button class="btn1" onclick="showBtn2()">
            Show Button 2
        </button>
        <button class="btn2" id="btn2"></button>
    </body>
    <script type="text/javascript">
        const btn2 = document.getElementById("btn2");

        function showBtn2() {
            btn2.style.display = "auto";
        }
    </script>
</html>

Advertisement

Answer

There is no auto display is CSS. As tarkh mentioned in his answer, display block would insert the new button below the initial button, and other display options would have other behaviors. But the display property does not have a value auto.

This may be my opinion, but I think modern websites shouldn’t use the onclick function for events. We should separate our HTML, JS and CSS. This helps with reusability. https://en.wikipedia.org/wiki/Unobtrusive_JavaScript

So I would create a solution that uses an event handler in the Javascript. Something like:

window.onload = function(){
const btn2 = document.getElementById("btn2");
const btn1 = document.getElementsByClassName("btn1");

    for(let i = 0; i < btn1.length; i++) {
        btn1[i].addEventListener('click', function(){
            btn2.style.display = "block";   
        })
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement