Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript don't save style properties

I have a problem with my site. I want to show a div on button click and hide it on another button click so I use JavaScript functions

    function DisplayMessage() {
        var messagebox = document.getElementById("messageConfirmation");
        messagebox.style.display = "block";
    }
    function HideMessage() {
        var messagebox = document.getElementById("messageConfirmation");
        messagebox.style.display = "none";
    }

but when I use them <div> shows and hides in only a moment, and then appears/disappears again, I really don't know what can cause such a problem so i will be really thankful for your answers. Full HTML page code:

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <style type="text/css">
        div.wrap {
            width: 850px;
            margin: 0 auto;
        }
        div.messageBox{
            display:none;
            width:500px;
            height:60px;
            background-color: rgb(200, 200, 175);
        }
    </style>
    <script>
        function DisplayMessage() {
            var messagebox = document.getElementById("messageConfirmation");
            messagebox.style.display = "block";
        }
        function HideMessage() {
            var messagebox = document.getElementById("messageConfirmation");
            messagebox.style.display = "none";
        }
    </script>
   </head>
    <body>
    <div class="wrap">
        <div class="messageBox" id="messageConfirmation" >
            <p>Message</p>
            <form>
                <button onclick="HideMessage()">HideME</button>
            </form>
        </div>
        <div>
            <form>
                <button onclick="DisplayMessage()">ShowMe</button>
            </form>
        </div>
    </div>

</body>
</html>
like image 237
MasterUZ Avatar asked Mar 06 '26 20:03

MasterUZ


1 Answers

By default, <button> inside a <form> element will act like a submit button, so once your code runs, the form is submitted and the page is refreshed, so it goes back to its old state. Change its type to button in order to achieve what you want:

<button type="button" onclick="HideMessage()">HideME</button>
like image 189
Rajaprabhu Aravindasamy Avatar answered Mar 09 '26 11:03

Rajaprabhu Aravindasamy