Show and hide Div with Javascript

Many times it has been seen that, we are in search of creating the dynamic content, which is visible on certain button click or checkbox selection. If we search on the internet we can find too many solutions to resolving this issue.

Today I am going to demonstrate here, how can we hide or show div with pure JavaScript?.

Here is step by step procedure:

1) Create a HTML file for browser view and save it as index.html

<!doctype html>
<html>
 <head>
  <title>Show and hide div with JavaScript</title>
  <script src="show.js"></script>
 </head>
 <body>
<div id="newpost">

This div will be show and hide on button click</div>
<button id="button" onclick="showhide()">Click Me</button>
</body>
</html>

Download


2) Create a JavaScript file for show and hide Div and save it with show.js

     function showhide()
     {
           var div = document.getElementById("newpost");
    if (div.style.display !== "none") {
        div.style.display = "none";
    }
    else {
        div.style.display = "block";
    }
     }

Download


Thats all done, now you can show and hide your div on button click.



  • fgdf

    dsfsdfdsfds

  • Woopher

    Thank you! Works perfectly. But this text is shown by default.
    How can you make it default hidden and when press button to show it?

    • mano

      dsssf

  • Ebin Thomas

    Thank u it is very much useful

  • mano

    thank you show and hide is perfectly worked …

  • quarter

    how can you set it so that the button is hidden to start?

  • http://www.html5andcss3.org/ swapnil raja

    Thanks for suggestion. I’ve modified it.

  • http://www.comment-devenirriche.com/ Comment DevenirRiche

    Working perfectly, thank you ..

  • SS

    OK, but if I want to close each div parent (NB! ‘this’ keword)? For examle how this jQuery code will be in pure JavaScript:

    $(function () {

    $(‘.x-close’).click(function () {
    $(this).parent().hide();
    });

    });

  • harsh

    hey, i want same things but without any button? it’s possible

Show Buttons
Hide Buttons