Useful Resources
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses
Hide and Show

Appear or Disappear using Javascript


The Code


<head>
      <script type="text/javascript">

            function hide(elem) {
                  document.getElementById(elem).style.display = "none";
            }

            function show(elem) {
                  document.getElementById(elem).style.display = "block";
            }

      </script>
</head>

<body>
      <a href="javascript: hide('myDiv');">Hide</a>
      <a href="javascript: show('myDiv');">Show</a><br /><br />

      <div id="myDiv" style="height:100px; width:100px; background-color:#990000;"></div>
</body>


Code in Action


Hide   Show



Explanation

With CSS, we can change the "display" of an element. Setting "display:none;" would make a div disappear. Setting "display:block;", while not necessarily intended to make something appear, WILL make it appear if it was previously set to "display:none;".

But - if we want it to disappear or reappear on the fly, we need to use Javascript. Luckily, Javascript allows us to change CSS.

In the example above, we have 2 links. The first calls a Javascript function that tells our object to change it's CSS to "display:none;". (You'll notice, setting CSS via Javascript looks a bit different than setting it in CSS.) The second does the same thing, but sets the display to "block" instead.

In-class Exercise

You do not have to just make a single DIV or IMG appear/disappear - what if you made a div with a bunch of things in it, then made that container DIV display appear/disappear?

Part 1 (the setup):
  1. Create a <div> with id="container" (don't forget to add a close </div> as well)
  2. Set it's height and width with CSS to 500px wide and 400px tall
  3. Set it's background-color to #CCC
  4. Center it using margins: margin: 50px auto; /* This will move it 50px from the top, and set it's left and right margins to "auto", which will center the div */
  5. Create two divs inside of the "container", and give each one an id of your choosing, and set them to 50px wide by 50px tall.

Part 2:
  1. Set the container box to position:relative;
  2. Set the position of the small inside-boxes to to position:absolute;
  3. Change the top or bottom and left or right properties of the inside boxes to position them around inside the container box.
  4. Try setting some to negative pixels: top: -25px; for example - what happens when you set them to negative pixels?

Part 3:
  1. Use the code above to show/hide the container box - you should notice that it shows/hides the boxes inside of it as well!
  2. Try making the container or one of the inner boxes disappear when you rollover something on the page and reappear when you roll outside of it.


How could you use this in your project? What other applications could it have?

Check out: http://www.w3schools.com/CSS/css_examples.asp

[BACK to RESOURCES]