how to hide/show something on the button click using basic javascript

Simple HTML and CSS markup are provided to just visualize what is happening as well as the javascript code for hiding this element is given below with the explanation of all the snippets(you can copy from snippets by clicking on copy).

In markup, I have created one p tag with para id to make this program as simple as possible so that we can access this id through javascript which you will see in javascript snippet .

<div class="container">
        <p id="para">
            Hi if you click the button i will disappear! please don't click it No.......(kidding)
        </p>
        <button id="btn" onclick="toggleHide()">Show/Hide</button>
    </div>

So, to give some better look to the button and the para I have used some basic CSS.

    <style>
        #para{
            color: black;
            background-color: pink;
            padding: 5px;
            margin: 5px;
        }
        #btn{
            padding: 10px 13px;
            background-color: red;
            color: white;
            border: 2px solid black;
            border-radius: 8px;
            cursor: pointer;
            display: block;
            margin: auto;
        }
    </style>

In javascript, as you can see we have accessed the p tag using its id and we gave one mouse event named onclick and defined one function to it named togglehide(you can use any name) which will make the function call when we click on the button using the mouse so function gets called, now when the function gets called here we have some conditions in it which specify that if the display style of para is not none it means that if para is visible then make it none(make it invisible) and in the else part it will make the display style of the para block so than the para would be visible. hope you know the concept of display block and display none.

<script>             function toggleHide() {             let para = document.getElementById('para'); if(para.style.display != 'none') { para.style.display = 'none'; }             else{para.style.display = 'block';} </script>

O/P before clicking the button

O/P after clicking the button

2 thoughts on “how to hide/show something on the button click using basic javascript”

Leave a Comment

Your email address will not be published.

Scroll to Top