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)
        <button id="btn" onclick="toggleHide()">Show/Hide</button>

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

            color: black;
            background-color: pink;
            padding: 5px;
            margin: 5px;
            padding: 10px 13px;
            background-color: red;
            color: white;
            border: 2px solid black;
            border-radius: 8px;
            cursor: pointer;
            display: block;
            margin: auto;

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( != 'none') { = 'none'; }             else{ = '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