Hide/show html elements using CSS and Javascript

Published:
Updated:
Sometimes, web designers want to do some "fancy" stuff on their pages, for example, toggle and allow the display of certain elements (say a form, or pictures).It not only provides fancy feeling to users, but could also make them feel a clear and simple layout. And here's how you do it.


In CSS, the style "display" can be applied to all html elements. It allows a wide set of values but what we concern today is "display: block" and "display:". Setting the value block allows an element to generate a principal block box, in other words, it will be shown. Setting it to none do the opposite, this value causes an element to generate no boxes in the formatting structure, i.e, the element has no effect on layout. You may get the idea at once and know what you have to do is to switch the display style's value, or switching the class of an elements belongs. For the latter approach, you can define something like

 
<style>
                      .open {
                      	display: block;
                      	}
                      .closed {
                      	display: none;
                      	}
                      </style>

Open in new window


But you have to switch the status at runtime, so the help of javascript is required.
Say, you have a div that wanted to be shown if user have checked a box, then you can do the following

 
Enable div ? <input type="checkbox" name="enableDiv" onclick="this.checked?document.getElementById('mydiv').className='open':document.getElementById('mydiv').className='closed';"/> 
                      <div id="mydiv" class="closed" style="border:1px solid #A0A0A0;height:50px;width:80px;" >
                      <!---contents here -->
                      I m here!
                      </div>

Open in new window


By clicking the checkbox, the div will be shown/hide according to the checkbox's status.


Here's another example that use this technique, but this time it behaves like the folder list in file managers. Sublists can be expanded or collapsed upon user clicking the expand/collapse box.

 
<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd">
                      <html>
                      <head>
                      <meta http-equiv=content-type content="text/html; charset=utf-8">
                      	
                      <script language="JavaScript">
                      	
                      function toggle(id){
                          ul = "ul_" + id;
                          img = "img_" + id;
                          ulElement = document.getElementById(ul);
                          imgElement = document.getElementById(img);
                          if (ulElement){
                                  if (ulElement.className == 'closed'){
                                          ulElement.className = "open";
                                          imgElement.src = "collapse.gif";
                                          }else{
                                          ulElement.className = "closed";
                                          imgElement.src = "expand.gif";
                                          }
                                  }
                          }
                      	
                      </script>
                      	
                      <style>
                      	
                      .open {
                      	display: block;
                      	}
                      .closed {
                      	display: none;
                      	}
                      li {
                      	list-style-type: none;
                      	padding-top: .2em;
                      	padding-bottom: .2em;
                      	}
                              
                      li img {
                      	vertical-align: middle;
                      	}
                      	
                      </style>
                      	
                      </head>
                      <body>
                      	
                      <ul class="open">
                          <li id="item1"><a  onclick="toggle('item1');"><img src="expand.gif" alt="" id="img_item1" border="0"></a>Item 1
                                        <ul id="ul_item1" class="closed">
                                                <li id="item1_1"><img src="solid.gif" alt="" border="0">Item 1.1</li>
                                                <li id="item1_2"><img src="solid.gif" alt="" border="0">Item 1.2</li>
                                        </ul>
                          </li>
                          <li id="item3"><a  onclick="toggle('item3');"><img src="expand.gif" alt="" id="img_item3" border="0"></a>Item 3
                                <ul id="ul_item3" class="closed">
                                        <li id="item3_1"><img src="solid.gif" alt="" border="0">Item 3.1</li>
                                        <li id="item3_2"><img src="solid.gif" alt="" border="0">Item 3.2</li>
                                        <li id="item3_3"><img src="solid.gif" alt="" border="0">Item 3.3</li>
                                        <li id="item3_4"><img src="solid.gif" alt="" border="0">Item 3.4</li>
                                        <li onclick="alert("hi");" id="item3_5"><img src="solid.gif" alt="" border="0">Item 3.5</li>
                                </ul>
                          </li>
                          <li id="item4"><a  onclick="toggle('item4');"><img src="expand.gif" alt="" id="img_item4" border="0"></a>Item 4
                                <ul id="ul_item4" class="closed">
                      	
                                </ul>
                          </li>
                      </ul>          
                      	
                      </body>
                      </html>

Open in new window

solid.gif
collapse.gif
expand.gif
1
9,118 Views

Comments (9)

Commented:
Grrr, only one of my attached code-blocks was posted :( So, the missing method is attached to this post.
function attachEventHandler(element, type, handler) {
	if (element.addEventListener) element.addEventListener(type, handler, false); //Most modern browsers
	else if(element.attachEvent) element.attachEvent('on' + type, handler); //IE
	else element['on' + type] = handler; //Old browsers
}

Open in new window

I'm a newbie but I have all the books. Including all the jQuery ones that have methods for this too, but of course one should learn how to address the DOM too. Even if jQuery hides much of that for us.

 but being a xTalk programmer for years, I think I can grok your functions well enough... If I understand the above correctly, the  

<div id="enableDiv"> clickable button here...</div>  

will  toggle the display of <div id="mydiv">Some Box to Hide or Show</div>

right?

I have the additional challenge in my context of needing to have this particular div remain hidden for the duration of the session across the user session where he may be traversing more than one page which has that same div... But I will take this to the actual Expert's exchange forum as I'm not sure that comments are the right place for such a dialog...


thank you!  I think I get it

Commented:
Fortunately knowing one programming language immediately makes it that much easier to understand the next :)

You got the idea, which isn't that much different from what you had before, the main difference being that javascript now needs to find the element and attach itsself instead of the element telling the javascript code to attach to it. The importance being separation.

I will take this opportunity to take your knowledge one step further (even some so-called js experts don't get this concept):
Some user-events only happen when the user deliberately undertakes them, the one of main interest being the click event, as opposed to the hover-event, which spawns all the time all over the html more or less unconsciously...
As a result it is actually quite easy to capture click events more globally, I often even go as far as just catching all clicks anywhere in the body element (have a look at the linklistener I linked). There are two major advantages to such a global approach:
1. You only attach one event-handler and the real work happens only when a user clicks, even if there's hundreds of links on the page, as opposed to a lot of work happening at the start when the script attempts to find all relevant elements...
2. When additional elements are added to the page due to an ajax-call, the event-handler will still see them without any extra effort.

The added complexity for the developer is that you need to 'introspect' each click-event to see if it is an element that you want to react upon... On the up-side, you can invent convenient handler to which you can quickly add new event types. Again, the linklistener I linked earlier is a good example. It reacts to all click-events within the body element, checks if the element that was clicked on is a <a .../> element and also checks if that element has a rel-attribute. If both are valid it then checks if there's a known handler for that rel-attribute and calls it. The obvious use-case it catching all links with rel="external" to pop up in a new window...

Good luck on your voyage in the wonderful world of JavaScript in the UI :)
Excellent insight on that global click listener. "Sweet"  for efficiency. Thanks for taking the time to share. If I could award points here I would...

hmm I don't see the EE option to add to my knowledge base, So I'll copy this to my local JS tips library.

Cheers from Kauai

Commented:
@MageWind, 'visibility' works in a bit different way, it doesn't display content inside of tag ('visibility:hidden'), 'display' doesn't display tag and content inside ('display:none').

View More

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.