<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Hide/show html elements using CSS and Javascript

Published on
11,742 Points
8,642 Views
1 Endorsement
Last Modified:
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
Comment
Author:quincydude
9 Comments
LVL 3

Expert Comment

by:MageWind
You can do something similar using the css property "visibility"
0
LVL 17

Expert Comment

by:mreuring
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 :(
0

Expert Comment

by:Sivakatirswami
@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

0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

LVL 17

Expert Comment

by:mreuring
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>

Open in new window

0
LVL 17

Expert Comment

by:mreuring
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

0

Expert Comment

by:Sivakatirswami
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
0
LVL 17

Expert Comment

by:mreuring
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 :)
0

Expert Comment

by:Sivakatirswami
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
0
LVL 8

Expert Comment

by:Zado
@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').
0

Featured Post

Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Join & Write a Comment

In this tutorial viewers will learn how to define a gradient in CSS. Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Gradient. Define the background as "linear-gradient(to right, #ee3668, black)". Ensure you …
In this tutorial viewers will learn how to style a decorative dropcap for the first letter in a paragraph using CSS. In CSS, create a new paragraph class by typing "p.fancy": Then, to style only the first letter of the first sentence, include the ps…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month