The Netlobo logo - a Nevada desert landscape

Comments for Showing and Hiding a DIV using CSS and Javascript

< Back to the article

82 comments for this article.

RSS Feed Icon Subscribe to the comments for this article

Posted: 2007-07-10 15:04:24 by Goo
Very useful, thanks a lot! I will use it at videofindr.com to hide and show description when is too long.
Posted: 2007-07-10 15:23:31 by lobo235 - Netlobo Staff Member
We're glad you found it useful. Thanks for stopping by!
Posted: 2007-07-11 19:14:31 by Paul
Thanks for this article. Very simple, clear and well-explained.
Posted: 2007-07-12 13:46:35 by Thomas
Very useful! I had a function but it only worked in Firefox. This method works also in IE so ... thank you very much !
Posted: 2007-07-15 05:32:24 by Skinner
Thank you very much! I had been looking all over for something this simple!
Posted: 2007-07-16 18:37:32 by Warwell
Great way to do this, thanks fellas.
Posted: 2007-07-31 15:04:13 by kaps
Thanks for the article. I liked this article for its explanation in simple and clear way.
Posted: 2007-08-01 14:03:53 by Tyran
A simple script that is just what i was looking for. Until Firefox catches up with IE7in being able to 'disable' a div this will do nicely. Cheers!
Posted: 2007-08-03 15:51:13 by nanny
I used the code thank you
Posted: 2007-08-10 16:00:31 by cdp
This script works really and I appreciate your sharing it. However, it wasn't working for me in Safari 1.3.2. I did some research and finally found the reason here: http://dev.mootools.net/ticket/51

Hope this helps anyone else who is struggling with the same issue. A workaround was simple using the same code.
Posted: 2007-08-10 16:03:17 by lobo235 - Netlobo Staff Member
The script seems to work fine in my version of Safari (3.0.3). It is good to know there is a workaround for older versions of Safari.
Posted: 2007-08-13 20:51:11 by geekaba
Thank you! I'd been half-heartedly looking for such a script and this just makes it cut&paste easy!
Posted: 2007-08-22 12:20:30 by shadowfax
This was a great article, easy to implement. I had to make a few modifications to apply it to a drop-down list selection instead of a link but it was exactly what I was looking for nonetheless, and I got it to work, which is more then I can say from some of the more recent code examples I have found on other sites. I bookmarked this site and will forward the URL to our contractors and my fellow co-workers. I especially enjoyed the fact that I could get answers quickly without all the B.S. about having to, ?login? or ?create an account? stuff that is on most other websites. Honestly, I always pass by all those other sites and look for sites like yours. Wow! A site I can actually get answers from without having to enter in all my info. Kudos to you! Netlobo.com rocks!
Posted: 2007-08-22 13:26:06 by Adam
Here's a quick hint:

This code is GREAT, except it gave me trouble in Safari. After much head scratching I came up with an easy solution for safari.

Essentially, the function needs to be run once on the onload (for each div) but ONLY for safari. So I borrowed some browser identification code, detect for Safari in the BODY onload, and then just run the function once per div if it's Safari. Work's like a charm - now I've got 100% compatibility with IE5, IE6, IE7, Safari, Firefox
Posted: 2007-08-22 13:30:22 by DuncanM
Fantastic little piece of code. It's snippets like this that keep the internet a lovely place to go :D One thing I would be interested in, is saying for example you have a large number of divs on a page that could be hidden/revealed (1 at a time) if there was anyway that when you clicked to show 1 div, any other divs that were previously open would shut automatically, without having to close the previous one first.

Thanks again
Posted: 2007-08-22 13:32:36 by lobo235 - Netlobo Staff Member
I put together an example of how to show one DIV from a group at a time and hide all the rest. The example is located here:
http://www.netlobo.com/media/examples/div_hiding_test.html

Thanks for all the great feedback so far on this article from everyone.
Posted: 2007-08-22 14:04:30 by raymondo
i was wondering how i can make this hidden until somebody clicks a link? is that possible?
Posted: 2007-09-12 15:19:15 by Phil
raymond, adding "display: none;" to the CSS for each div will keep it hidden until somebody clicks the corresponding link.
Posted: 2007-09-19 14:24:59 by Nick
great work! your site is awesome in general. code works great and simple.

thank you.
Posted: 2007-10-29 10:07:21 by Mani
This is a nice little script, but has no fall-back if scripting is disabled in the browser. You can work around this by putting your CSS that sets display:none in its own stylesheet, and then writing the stylesheet link via javascript...

[showhide.css]
div#commentForm
{
margin: 0px 20px 0px 20px;
display: none;
}
[/showhide.css]

<script language="JavaScript" type="text/javascript">
document.write('<link href="/css/showhide.css" rel="stylesheet" type="text/css" />');
</script>
Posted: 2007-10-29 10:08:18 by lobo235 - Netlobo Staff Member
Mani, that is a great idea. Thanks for the comment.
Posted: 2007-11-13 06:03:25 by Manpreet
fantastic code, really simple and easy to use. thanx a lot.
Posted: 2007-11-13 21:13:43 by Mark
Ow great, been trying for hours to figure this out ^^" Little less satisfying but a lot faster with this example :D I'll put your name above the script ofc :)
Posted: 2007-11-29 22:40:08 by JohnK
You can have the DIV hidden on load without using a style sheet by simply issuing a

<script language='JavaScript'>
toggleLayer("commentForm");
</script>

after the DIV.
Thanks for the script!
Posted: 2007-12-28 13:23:03 by Mitchell
Thank you for posting this script! I was fussing around with mootools.net to get this effect, but this script is so much more elegant.

Would you mind updating this article to reflect the issues a couple of the commenters had with Safari? I'm interested in their work-arounds, but unfortunately I couldn't glean enough from their comments to add them to my page. Keep up the great work!
Posted: 2008-02-02 12:04:01 by Bsquared
I read this article with great interest as I am redesigning a site to dispense with iframes. My concern is whether search engines indeed find the hidden div text as my research on example pages is inconclusive. Most are old pages.

My appreciation for responses.
Posted: 2008-02-02 12:04:51 by lobo235 - Netlobo Staff Member
Bsquared,

The search engines will index the content even though it is hidden by CSS because it is still on the page.
Posted: 2008-02-06 09:05:40 by Bsquared
Lobo235 - thank you for the response. I have run a test on you sample page and my question is this: Can I embed a small html page in the div (so far no luck - always jumps to new page)?

I have numerous pages in this site that I call into the aforementioned iframes. If I sound like a newbie, it's because I am. i have learned this stuff over the past few months and I would like to redo my first and only site. Your help and response is greatly appreciated.
Posted: 2008-02-06 09:07:50 by lobo235 - Netlobo Staff Member
Bsquared,

You must make sure that you are not using an iframe inside of the hidden DIV. You will just want to put the HTML code in the DIV directly and then use CSS to hide the DIV. Then, you can use the javascript function in the article to show/hide the DIV.

I hope this helps.
Posted: 2008-02-14 08:22:18 by TomBajzek
What is the meaning of the following statement in your code?:

vis.display = (vis.display==''||vis.display=='block')?'none':'block';

I've not found any example of this assignment structure in my JavaScript book, nor online. I need to modify your solution for my similar, but not identical, purpose, but I don't understand this.

Thanks for your help,
Tom
Posted: 2008-02-14 08:24:59 by lobo235 - Netlobo Staff Member
TomBajzek,

That statement is a shortcut for an if-else statement. It works as follows:

Expression?true part:false part

Where if the Expression is true then the true part is returned and if the Expression is false then the false part is returned. Many programming languages have this same shortcut including C++, Java, and PHP so it's a good tool to have on the belt.
Posted: 2008-02-19 12:40:23 by richard52
The script worked but it only finds one id per page than stops. It dosn't change all the id's. I have two seperate div's one for current data and one for past. Icould put them both in the same id but I think I would like a radio button to select to display current or past data. Any ideas how to do that? Thanks
Posted: 2008-02-19 12:43:52 by lobo235 - Netlobo Staff Member
You should only ever have 1 element with a specific id. The W3C HTML spec states that the id of an element should be unique for the whole document. See here: http://www.w3.org/TR/html401/struct/global.html#h-7.5.2

I would suggest that you give a unique id to each div and then when one radio button is clicked you call a function that hides all the divs and then shows the one that corresponds to the radio button the user clicked.

I hope this helps.
Posted: 2008-03-10 16:15:25 by mastoll
I love it so far!

I have added a "close this window" link inside of the <div> which opens via your java snippet.

The <div> contains a video which plays upon opening.

When I close the <div>, the video continues to play in the background i.e. I can still hear the sound track.

Though the question is a bit off of your topic here, can you comment on how to stop the video when the <div> closes?
Posted: 2008-03-10 16:19:39 by lobo235 - Netlobo Staff Member
mastoll,

You could probably get the video to stop playing by removing it from the DOM when the div is closed. If you want the user to be able to see the video again after that you will have to add the video back into the div. See http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/ for some code that might help you implement this.

Thanks for stopping by the site and taking the time to comment!
Posted: 2008-03-17 09:02:19 by mxxx
cheers mate. nice bit of code there.
Posted: 2008-03-18 23:33:13 by Chris
Great script.

Is there a way to make it toggle different divs?

I have a long survey that I'd like to use this on and I was hoping to implement buttons that would do the following:

Starting with the first section of the survey, hide the remaining sections which are enclosed in divs labeled survey1, 2, & 3.

Click a link that hides section 1 and opens section 2, etc.

I thought maybe adding a ('divID', 'divID') to the toggle call would suffice, but my JS skills are low and I don't really know how to do that.

Lil help?

Thanks!
Posted: 2008-03-24 11:26:49 by Ryan
This was really helpful! I'm having trouble though on IE6 - maybe because I'm using java rollovers and this script at the same time? Maybe a conflict?

http://www.sparkssullivan.com/final/
Posted: 2008-03-24 11:37:57 by lobo235 - Netlobo Staff Member
It looks like you have named your section images the same as the DIVs you are displaying and hiding. IE6 is dumb because it interprets the NAME attribute to be the same or similar to the ID attribute. So when you call toggleLayer( 'news' ) it is getting the element that has the NAME attribute set to 'news' and not the element that has the ID attribute set to 'news'. It does this because the news images comes before the news div in the document. You can solve the problem by changing the names of your images so they are different than the DIVs you are toggling.

IE6 is lame.
Posted: 2008-03-24 23:26:39 by DomenLombergar
Thanks, this article really helped me. Finally I can hide some useless stuff :)
Posted: 2008-04-07 06:19:49 by Webflo
Thanks for this great piece of coding. It is little pieces like this that really can help with development. I do appreciate the this blog entry very much. This really allows us to clean up a lot of the useless div code.
Posted: 2008-04-07 11:05:37 by Robbie
This is great, thank you! I'd like to use this to turn a tag cloud on/off for our publication, but I wonder how we could make it so the site remembers a user's preference. i.e., how can I combine this with a cookie?
Posted: 2008-04-12 10:35:51 by Nasip
This is great, Thank you!
Posted: 2008-04-18 09:06:10 by Mike
Thanks for this tutorial - it made the work that I'm doing <i>so</i> much easier. I've been trying to figure out how to do this and now I have a solution.
Posted: 2008-04-24 07:18:39 by Phil
Perfect, I agree with everyone else, very useful.

I would like the DIV's that appear to also contain a list of links to produce a second set of hiden DIVs...if that makes sense.

Is this easy to achieve?
Posted: 2008-04-28 08:23:56 by Melanie
Hi

Just wanted to say thankyou for the great script.

First of all I like to say that I am by no means a programmer, but manage well by following example.

I had my Network Usage Policy stored in the database and figured that since it doesnt change much I should put it a page by itself and in such a way that the page doesnt have to load each time a visitor views a particular item and it would lessen the calls to the database. I also needed to save space on the page and this script has really helped me tremendously.

Thank You so much
Posted: 2008-06-17 21:43:59 by Mike
Very helpful. Thanks for taking the time to write this up.
Posted: 2008-06-23 09:08:19 by LukasTaylor77
Hi! Thanks for the great script.

Can anyone please post the workaround for older versions of Safari for us non-Javascripters???

Would be greatly appreciated!
Posted: 2008-07-09 09:53:55 by StoneDeft
here's one that does thesame with no java but dhtml and css styles


<div id="contents">
this is the div to be replaced
</div>

<div id="replace" style="display:none">
this div will replace the contents div
</div>

<span style="cursor: hand" onClick="document.getElementById('contents').innerHTML=document.getElementById('replace').innerHTML">My Link</span>

just copy paste the code and see it work. well hope this helps
Posted: 2008-07-21 23:20:28 by Flashguy
Excellent script, I'm having one problem with it though. I'm using the script to show/hide a div with a flash movie in it, everything works great in firefox, but in IE you can still hear the video playing after it is hidden.

I can't seem to figure out why it works properly in FF3 but not IE7, any help is appreciated. Thanks again for the great script!

T
Posted: 2008-07-25 08:45:45 by Matthew
Thanks, very useful!
Posted: 2008-08-04 10:16:08 by PeterDeP
Searching the web for toggling DIVs I came across this thread. But what I needed was a function that was generic to show or hide any number of DIVs on a page, even if they were nested. This would allow considerable 'conditional branching logic' to be built into an HTML page depending on a vistor's choices.

Hours of Web searching provided nothing suitable; so I wrote one myself. It may be of interest to others here [or it may not :( ]. As written here is is highly commented and can be reduced by at least 60% for a running version. Also it is set in demo mode to print out to screen the show/hide actions. Judicious adding removing of the comment lines swiftly converts it to a 'live' version.

A certain [minimal] amount of parameter error trapping has been added; this could be developed as needed.

To call the function simply list the DIV ids prefixed by a plus for open or minus symbol to close, no spaces and separated by commas as here:

<script langauge="JavaScript" type="text/javascript">
switchDivs(" this, is,-an, unlimited, -list,-of,-div, IDs,-split, by, commas, without,-any, spaces");
</script>


The function, set in the HEAD of the page follows:

<script langauge="JavaScript" type="text/javascript">
function switchDivs(idParams){
	// Parameters are unlimited div IDs prefixed with a plus or 
	// minus symbol, separated by commas and without *any* spaces.
	// -----------------------------------------------------------
	// Split the incoming parameters and store in array
	var idArray = idParams.split(',');
	// Get number of passed in parameters in the array
	var numberDIVs = idArray.length;
	// Set up a loop counter and variable to hold the div ID
	var ctr; divID = "";
	for (ctr = 0; ctr < numberDIVs; ctr  ){
		// Get full array member comprising ' ' || '-' symbol prefix   div ID 
		divID = idArray[ctr];
		// Get the inital char into variable for later use
		showHide = divID.charAt(0);
		//Now trim it off
		var lengthID = divID.length;
		var simpleID = divID.substr(1,lengthID);
		// Error check: should be eith a ' ' char or a '-' char
		if (showHide == ' ' || showHide == '-' ){
			if (showHide == ' '){
				// Hide the div and contents - NOTE: uncomment this line when in use
				// document.getElementById(simpleID).style.visibility="visible";
				// This next line not required - DEMO purposes only - remove or comment out for use
				document.write("
" showHide " symbol = SHOW div with ID: '" simpleID "'") ; } else { // Hide the div and contents - NOTE: uncomment this line when in use // document.getElementById(simpleID).style.visibility="hidden"; // This next line not required - DEMO purposes only - remove or comment out for use document.write("
" showHide " symbol = HIDE div with ID: '" simpleID "'") ; } } else { // There's an error - print it out document.write("

switchDivs function - parameter error! DIV id is: >>" divID "<<
")} } } </script>
Posted: 2008-08-12 15:09:50 by huminuh83
This worked great for me. Easy to follow and very useful. Thanks so much!
Posted: 2008-08-19 09:05:09 by cyberj
Thanks for the code, it's really nice.

I just have some problem, I need to hide/show 5 div tags when clicking a menu then show 1 appropriate div. I also need to do this on page load.

I tried PeterDep's code:

<li onMouseOver="this.className='hover'" onMouseOut="this.className='';"><a href="javascript:switchDivs(" div1,-about,-title1,-title2,-title3,-title4");">menu1 </a></li>

but nothing happens.

Please help with this, or if there's a way to do this on lobo's original code, that will be great.

Thanks.
Posted: 2008-08-27 08:28:54 by Tony
Thanks, worked great.
Posted: 2008-10-15 08:34:34 by fireborn
Just what I was looking for...
Simple useful and effective!
Works in all major browsers tests too.

Posted: 2008-10-31 08:24:42 by Sibtain
This is really very good stuff.
I was just looking for this ..............................
Great!
Posted: 2009-01-06 11:23:28 by Toleg
Thank you! This is the best realization that I found in the web. It's very compact and powerfull.
Posted: 2009-01-29 16:10:06 by denise
This article helped my create a fax form for an application. I was able to hide the buttons on the page when the print button was clicked.
Posted: 2009-02-10 07:49:46 by billythekid
Thanks for this. Just picking up JS (coming from mIRC and PHP) for the first time and this was exactly what the doctor ordered.

Have implemented it in blogshares blog pages and on my own sites. I'm going id="" mental now!

I'm going to take a look into scriptaculous stuff to see if I can add an fade or slide effect to the disappearance now.

One thing I'd note is that the code on it's own doesn't validate without (for example...)
<script type="text/javascript">
/* <![CDATA[ */
function toggleLayer( whichLayer )
{
  var elem, vis;
  if( document.getElementById ) {// this is the way the standards work
    elem = document.getElementById( whichLayer );
}
  else if( document.all ) {// this is the way old msie versions work
      elem = document.all[whichLayer];
}
  else if( document.layers ) {// this is the way nn4 works
    elem = document.layers[whichLayer];
}
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
/* ]]> */
</script>


thanks again for giving me a nice start in Javascript.
Posted: 2009-03-15 15:26:50 by neverwish
After years of your writing still inspiring and so useful, thx for sharing this
It both solved getting my ideas working as teaching some base I was lacking
Posted: 2009-06-23 09:37:01 by Rajah
Thank you very much for this useful script. While it works flawlessly when I apply it on its original purpose (making appear something that is hidden), I tried to apply it the other way around (having a block appearing when the page loads, and then having the link hide it), and oddly it works only after two clicks on the link (rather than one). After those two clicks the switch function works normally, for each click. Any clues as to what I might have got wrong? Thank you in advance...
Posted: 2009-06-26 14:10:30 by Rajah
The comment posted by netlobo on 2007-08-22 links an example for the script to toggle on/off various divs at once (show one/hide all the other). However, it doesn't work as such in IE; here's the workaround:

isIE = (window.ActiveXObject) ? true : false;

function elemOn(elem_id){
if(isIE){if(document.getElementById(elem_id))
document.getElementById(elem_id).setAttribute("className", "unhidden");}
else{if(document.getElementById(elem_id))
document.getElementById(elem_id).setAttribute("class", "unhidden");}
}
function elemOff(elem_id){
if(isIE){if(document.getElementById(elem_id))
document.getElementById(elem_id).setAttribute("className", "hidden");}
else{if(document.getElementById(elem_id))
document.getElementById(elem_id).setAttribute("class", "hidden");}
}
function hideAll(){
for( var i = 1; i <= 7; i++ )
elemOff( 'team'+i );
}
function showAll(){
for( var i = 1; i <= 7; i++ )
elemOn( 'team'+i );
}
function showOne(elem_id){
hideAll( );
elemOn( elem_id );
}
Posted: 2009-07-06 08:53:50 by Simon
Hi, how can i set more then one id?
this works perfect with the div (id 9)
<a href="javascript:toggleLayer('9');"...

but i need something like

<a href="javascript:toggleLayer('9','1');".....

can you help me?

THANKS
Posted: 2009-07-09 07:15:54 by Rajah
Simon, did you try the following?
"javascript:toggleLayer('9');toggleLayer('1');"
Posted: 2009-07-11 22:17:11 by brokencode
Thank you very much. I was thinking this it use a very long and complex javascript :D
Posted: 2009-07-18 17:02:00 by Simon
Thank you so much Rajah
Posted: 2009-07-21 09:01:21 by Oliver
Great script. Perfect for what I needed to do. Thanks
Posted: 2009-08-03 10:38:14 by Mike
Thanks for a nice piece of code.

Is it possible to have a checkbox on the page that when clicked will collapse all the toggled layers?

Posted: 2009-08-18 13:37:29 by Nitin
Thanks for such nice article.

I got the sucess in hiding div tag. but after make it hidden text is hidden but placeholder of tag is still present. Is there any way to hide the place holder also?
Posted: 2009-12-01 23:43:41 by Richard
Thanx, this was very usefull !! Very elegant.
Posted: 2010-01-26 21:07:15 by Lee
Nice and simple, thank you.
Posted: 2010-04-11 15:41:00 by markus
That was exactly what i was searching for, very simple. :)
Thanks a lot.
Posted: 2010-04-12 08:56:28 by Greg
this script does not work on my site, I am not sure what I did wrong.

Main changes: I replaced ID with CLASS, Inserted the CSS in my external stylesheet.
It always says there is an error in the js.

My site is hidden from public eye (under development) but if you email me, I'm happy to show you.
Posted: 2010-05-11 18:43:02 by atlantawebdesign
Thank you for this tutorial, I am using it on one of my project now!
Posted: 2010-06-02 12:49:45 by tescovouchers
Excellent thanks, i couldnt figure out how to toggle the visible and none visible states, you solved my problem, cheers!
Posted: 2010-06-10 07:13:03 by codekidddo
simple and useful. thank you very much!
Posted: 2010-06-16 20:50:14 by shipping
Just the code snippet I was looking for. Thanks!
Posted: 2010-07-13 14:21:14 by Eiolon
I do my validation server side with PHP. When the form is submitted it reloads the page to display the error. Does anyone know how to make it so the DIV does not hide after the reload?
Posted: 2011-01-25 07:11:13 by Transport
A simple script that is just what i was looking for. Until Firefox catches up with IE7in being able to \'disable\' a div this will do nicely. Cheers!
Posted: 2011-02-18 07:16:12 by Xal
Nice. But i would call the function togglevisibility( ID ) or something cause your function name let\'s me think you work with the layers/z-index.
Posted: 2011-03-09 10:23:14 by Voraz
Great code. I\'ve been using it for a while and still find new uses for it. I was wondering if there is a way to pass the id from a link. I am using the code to show and hide different divs based on a top menu with only one defaulting to visible on page load. I would like to be able to create links to some of the hidden divs so that when a user clicks the link on a different page it would load my page with the menu and have a specific one visible instead of the default. I am thinking that somehow I would need to pass the div id with the url to the javascript on pageload but not sure how this would be done.

RSS Feed Icon Subscribe to the comments for this article

Post your comment for the Showing and Hiding a DIV using CSS and Javascript article:

Name (required) (letters and numbers only):
Email (required) (will not be published):
Website (include http://):
Comment (required): (HTML tags allowed: pre, strong, em, b, i)