How to Toggle Divs With Javascript

Web pages--which began as a simple way to transfer scientific papers to other people around the world--have blossomed into rich applications built for the Internet and Web browsers. One of the basic functions that allows Web pages to be interactive is the ability of Javascript to show and hide div, or division, elements on a page. For example, Javascript can be used to show an error message if something has gone wrong with your application.

Instructions

    • 1

      Copy and paste the following code into the head of your HTML document. This code looks for an HTML element with the ID "myDiv" and then hides it if it's visible or shows it if it's hidden:

      <script type="text/javascript">

      <!--

      function toggle_visibility() {

      var e = document.getElementById('myDiv');

      if(e.style.display == 'block')

      e.style.display = 'none';

      else

      e.style.display = 'block';

      }

      //-->

      </script>

    • 2

      Copy and paste the following code into the body of your HTML document. This creates the "myDiv" element and creates a link that will trigger the code from step 1 to run when you click on it:

      <div id="myDiv">This is the div that can be toggled</div>

      <a href="#" onclick="javascript:toggle_visibility()">Click to Toggle the Div!</a>

    • 3

      Open the Web page in your favorite browser and click the link in the page to toggle the div on and off.

Tips & Warnings

  • You can set the div's ID to anything you want, but make sure the ID in your div matches the ID in the JavaScript code.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured