Bright Java Tutorial

is brought to you by DoITBright LLC

Javascript

Show And Hide HTML Elements Using Javascript

We might want to show or / and hide HTML elements at a click of a button or any event that we may trigger. One of the ways to accomplish this is by front end programming. Let us look at the example below.

  <html>
    <head>
      <title>
        Show And Hide HTML Elements Using Javascript
      </title>
      <script type="text/javascript">
        function show() {
          var chk = document.getElementById('aDiv');
          aDiv.style.display = "block";
        }
        function hide() {
          var chk = document.getElementById('aDiv');
          aDiv.style.display = "none";
        }
        function showTxt() {
          var txtVal 
            = document.getElementById('txt').value;
          alert(txtVal);
        }
      </script>
    </head>
    <body>
      <div id="aDiv" name="aDiv">
        <pre>
      The quick brown fox jumped over the lazy dog.
      The quick brown fox jumped over the lazy dog.
        </pre>
        Just a textbox : <input type="text" id="txt" 
          name="txt" value="" />
      </div>
      <form>
        <input type="button" value="Show" 
          onclick="show();"/> 
        <input type="button" value="Hide" 
          onclick="hide();"/>
        <input type="button" value="Textbox Value" 
          onclick="showTxt();"/>
        <br/>
      </form>
    </body>
  </html>
                           
In the above example, we made use of the HTML <div> tag. A 'div' is a container for your HTML elements. It can also serve as a section to divide your HTML document. The elements that we wish to show and hide are few lines of texts and an HTML textbox. The above mentioned elements are surrounded by the <div> and </div> tags. We have a button that invokes the call on the function show(). This will make the elements inside the <div> and </div> tags show up. There is another button that invokes the call on the function hide(). This will make the elements inside the <div> and </div> tags to be hidden. Take note that the elements were just hidden but are still there. We do not need to recreate those elements. To prove this, we have another button that invokes the function showTxt() which we can try clicking this button while the elements are still hidden. You will notice that even though the textbox with an id of 'txt' cannot be seen as of the moment, when we click the button to show the value of that textbox, the value can still be retrieved by our showTxt() function.

In this lesson, we learned one of the possible ways to show and hide HTML elements and that is through the use of the HTML div tag plus manipulating it's attribute using Javascript.


Back