Hide/show html elements using CSS and Javascript

AID: 187
  • Status: Published

4310 points

  • Byquincydude
  • TypeGeneral
  • Posted on2008-11-20 at 16:37:58
Awards
  • Community Pick
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>
                                    
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen 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>
                                    
1:
2:
3:
4:
5:

Select allOpen 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>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:

Select allOpen in new window

Asked On
2008-11-20 at 16:37:58ID187
Tags

Hide

,

show

,

html elements

,

CSS

,

Javascript

Topic

Cascading Style Sheets (CSS)

Views
3109

Comments

Expert Comment

by: MageWind on 2009-12-17 at 16:04:21ID: 6914

You can do something similar using the css property "visibility"

Expert Comment

by: mreuring on 2010-03-23 at 12:19:45ID: 11564

I find it somehow ironic that you're explaining a 'best practice' in using classnames to trigger visual effects but then supply javascript code that uses the 'worst practice' of applying event-handlers inline :(

Expert Comment

by: Sivakatirswami on 2010-09-14 at 13:10:06ID: 19414

@mreuring:

OK, you have my attention: but constructive criticism is best accompanied with positive input. i.e. in this case, if applying JS event-handlers inline tis "worst" practice, then what is the "best practice" as you see it?  How would you do it

sigied : js newbie always looking for best practices; and currently needing to  hide and display of some div blocks

Expert Comment

by: mreuring on 2010-09-14 at 15:56:25ID: 19418

A long-winded introduction to event-handling, but an interesting read (I think) if you have little experience with it: http://www.quirksmode.org/js/introevents.html

Unfortunately there are some things in which PPK and me will never see eye-to-eye, his recommendation for using the traditional event handling being pretty close to the top of the list. So, hoping that even though you say you're a js newbie, I hope you can read the attached js fairly well :)

Attached is an extracted method from my own small event-handler methods (see http://www.windgazer.nl/projects/jsrepository/events.js for the whole script, most of the file is comments to explain it)

So, for starters I would have expected your first example to use something along those lines. Honestly, it's a little more writing, but that's only in such a short example :) This is only the beginning, the possibilities ahead are much more fun, check out http://www.windgazer.nl/projects/jsrepository/linklistener.js
Enable div ? <input type="checkbox" name="enableDiv" id="enableDiv"/> 
<div id="mydiv" class="closed" style="border:1px solid #A0A0A0;height:50px;width:80px;" >
<!---contents here -->
I m here!
</div>

<script>
attachEventHandler(document.getElementById("enableDiv", "click", function(e) {
  var e = e||event;
  var t = e.target||e.srcElement;
  var d = document.getElementById('mydiv');
  d.className=t.checked?'open':'closed';
});
</script>

                                        
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

Expert Comment

by: mreuring on 2010-09-14 at 15:59:16ID: 19419

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
}
                                        
1:
2:
3:
4:
5:

Select allOpen in new window

Expert Comment

by: Sivakatirswami on 2010-09-15 at 10:18:16ID: 19448

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

Expert Comment

by: mreuring on 2010-09-17 at 02:44:26ID: 19506

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 :)

Expert Comment

by: Sivakatirswami on 2010-09-17 at 18:22:13ID: 19548

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

Expert Comment

by: Zado on 2010-11-29 at 07:20:53ID: 21642

@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').

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top CSS Experts

  1. COBOLdinosaur

    213,892

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  2. LZ1

    169,513

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  3. DaveBaldwin

    108,635

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  4. ChrisStanyon

    101,266

    Master

    0 points yesterday

    Profile
    Rank: Sage
  5. tommyBoy

    65,616

    Master

    0 points yesterday

    Profile
    Rank: Genius
  6. kozaiwaniec

    57,116

    Master

    2,000 points yesterday

    Profile
    Rank: Guru
  7. nap0leon

    53,757

    Master

    0 points yesterday

    Profile
    Rank: Sage
  8. xmediaman

    50,100

    Master

    0 points yesterday

    Profile
    Rank: Guru
  9. jason1178

    49,680

    0 points yesterday

    Profile
    Rank: Genius
  10. SSupreme

    43,018

    0 points yesterday

    Profile
    Rank: Wizard
  11. Kravimir

    42,150

    0 points yesterday

    Profile
    Rank: Genius
  12. s8web

    40,064

    0 points yesterday

    Profile
    Rank: Sage
  13. therealteune

    35,300

    0 points yesterday

    Profile
    Rank: Wizard
  14. webmatrixpune

    30,818

    0 points yesterday

    Profile
    Rank: Guru
  15. HagayMandel

    27,880

    0 points yesterday

    Profile
    Rank: Guru
  16. zappafan2k2

    23,368

    0 points yesterday

    Profile
    Rank: Guru
  17. leakim971

    22,966

    0 points yesterday

    Profile
    Rank: Genius
  18. HainKurt

    20,000

    0 points yesterday

    Profile
    Rank: Genius
  19. jagadishdulal

    19,668

    0 points yesterday

    Profile
    Rank: Guru
  20. Proculopsis

    19,350

    0 points yesterday

    Profile
    Rank: Sage
  21. mplungjan

    19,232

    0 points yesterday

    Profile
    Rank: Savant
  22. basicinstinct

    19,026

    0 points yesterday

    Profile
    Rank: Genius
  23. anuradhay

    19,006

    0 points yesterday

    Profile
    Rank: Guru
  24. jtwcs

    18,808

    0 points yesterday

    Profile
    Rank: Master
  25. gurvinder372

    18,057

    0 points yesterday

    Profile
    Rank: Genius

Hall Of Fame