Follow this blog

Thursday, January 15, 2009

How to show and hide HTML elements using Javascript

This short article give explain how to show/hide HTML elements using jscript.There are two examples : first example use <div> tag to show and hide text when somebody click on link, second example show and hide table when somebody click on radio button. To find more javascript effects follow the link.

Show or hide text with click on hyperlink


To hide HTML element it should be inside <div>.

<div> tag should have style attribute in which is defined DISPLAY property.
DISPLAY property can have value "none" or "block".

If DISPLAY property value is none - the element will not be displayed.
If DISPLAY property value is block - the element will be displayed.

How it work (click on Show/Hide):
Show/Hide



This example hide or show text "This text was hidden" when hyperlink Show/Hide is clicked.

Related links

Hide or show div element - tutorial how to hide div tag with slightly simpler samples and code examples

Hide table row with javascript - How to dynamically hide or show entire HTML table and how to hide or show only one row in HTML table

Show or hide multiple divs - how to make one jscript function which can be called from multiple places on web page and how to hide multiple divs with only one click action

Demonstration of basic web effects with jQuery - in this article you can find demos and sample code for basic effect (hide, show, fadeIn, fadeOut, slide down, slide up and animate effect) functions in jQuery.





Code for example:

<a onclick ="javascript:ShowHide('HiddenDiv')" href="javascript:;" >Show/Hide</a>

<div class="mid" id="HiddenDiv" style="DISPLAY: none" >
This text was hidden
</div>

<script language="JavaScript">
function ShowHide(divId)
{
if(document.getElementById(divId).style.display == 'none')
{
document.getElementById(divId).style.display='block';
}
else
{
document.getElementById(divId).style.display = 'none';
}
}
</script>

We have hyperlink "Show/Hide" (inside <a> tag) which on click call Javascript function ShowHide.
JavaScript function ShowHide display or hide <div> with id "HiddenDiv".

Show <div> - document.getElementById(divId).style.display='block';

Hide <div> - document.getElementById(divId).style.display = 'none';

Inside <div> can be anything, in our case it is simple text but can be table, another <div> element, image...

If you want that your link text change to "Show" when a HTML element need to be showed and text "Hide" when HTML element need to be hided visit: javascript: Changing text

There is a link for simpler explanation how to Hide or show div element and change div visibility with three more demos.




Show or hide table when somebody click on radio button

In this example we will show first table when user choose radio button A with text "You select A,table tblA is shown". If user choose radio button B second table is displayed (tblB) and if radio button C is clicked third table is displayed.

You can test how it is working below:


Please, select optionABC



Here is code:


<script type="text/JavaScript">

<!--
function show(id)
{
if (document.getElementById(id).style.display == 'none')
{
document.getElementById(id).style.display = '';
}
}
//-->

<!--
function hide(id)
{
document.getElementById(id).style.display = 'none';

}
//-->
</script>


<table cellspacing="1" cols="3" border="0">
<tbody>
<tr valign="top" align="left">
<td width="202"><b>Please, select option</b></td>

<td width="481">A
<input type="radio" name="Option" onfocus="hide('tblB');hide('tblC');show('tblA');">
B
<input type="radio" name="Option" onfocus="hide('tblA');hide('tblC');show('tblB');return true;">
C
<input type="radio" name="Option" onfocus="hide('tblA');hide('tblB');show('tblC');return true;">
</td>
</tr>
</tbody>
</table>
<br>
<table id="tblA" style="DISPLAY: none" cols="1" cellpadding="2">
<tbody>
<tr valign="top" align="left">

<td>
You&nbsp;select A,
table
tblA is shown&nbsp;
</td>
</tr>
</tbody>
</table>
<table id="tblB" style="DISPLAY: none" cols="1" cellpadding="2">
<tbody>
<tr valign="top" align="left">
<td>
You&nbsp;select B, table tblB
is shown&nbsp;
</td>
</tr>
</tbody>
</table>
<table id="tblC" style="DISPLAY: none" cols="1" cellpadding="2">
<tbody>
<tr valign="top" align="left">
<td>
You&nbsp;select C, table tblC
is shown&nbsp;
</td>
</tr>
</tbody>
</table>


Let's take a look at code. JavaScript function show show HTML element.
Javascript function hide hide HTML element.
When user click on first radio button (A) table A is displayed while table B and table C are hided.

58 comments:

Neom said...

Hello and thanks for good script.

I have mini issue..

I create more this elements, but how make what if i show element 1, element 2 was auto hide?

Thanks.

Mark said...

I am not certain that I understand you well, but think that this is what you ask:

<a onclick ="javascript:ShowHide('HiddenDiv','HiddenDiv2' )" href="javascript:;" >Show/Hide</a>

<div class="mid" id="HiddenDiv" style="DISPLAY: none" >
This text was hidden
</div>

<br>

<div class="mid" id="HiddenDiv2" style="DISPLAY: none" >
This text 2 was hidden
</div>

<script language="JavaScript">
function ShowHide(divId, divId2)
{
if(document.getElementById(divId).style.display == 'none')
{
document.getElementById(divId).style.display='block';
document.getElementById(divId2).style.display='none';
}
else
{
document.getElementById(divId).style.display = 'none';
document.getElementById(divId2).style.display='block';
}
}

</script>

Anonymous said...

Hi and thanks for the great post.. very helpful.. Just wondering if you can do a variation for me..??

I want to have 3 radio buttons, being X, Y and Z.. If radio buttion X is selected text box 1 appears, if Y radio button selected text box 2 appears and if radio button z selected texbox 3 appears.. if the users presses Z, Y or Z the relevant text boxes appear and disappear etc..

Thanks alot and like the helpful info you have posted..

Mark said...

<head>

<script type="text/JavaScript">

<!--
function show(id)
{
if (document.getElementById(id).style.display == 'none')
{
document.getElementById(id).style.display = '';
}
}
//-->

<!--
function hide(id)
{
document.getElementById(id).style.display = 'none';

}
//-->
</script>
</head>

<body>
<table cellspacing="1" cols="3" border="0">
<tbody>
<tr valign="top" align="left">
<td width="202"><font style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial Narrow'"><b>SEX</b></font></td>
<td width="21">&nbsp;</td>
<td width="481"> <font style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial Narrow'">
Female</font>
<input type="radio" name="txtgender" value="female" onfocus="hide('biTbl');hide('maleTbl');show('femaleTbl');return true;" id="female">
<font style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial Narrow'">Male</font>
<input type="radio" name="txtgender" value="male" onfocus="hide('biTbl');hide('femaleTbl');show('maleTbl');return true;" id="male">Bi
<input type="radio" name="txtgender" value="bi" onfocus="hide('femaleTbl');hide('maleTbl');show('biTbl');return true;" id="male">
</td>
</tr>
</tbody>
</table>
<br>
<table id="femaleTbl" style="DISPLAY: none" cols="1" cellpadding="2">
<tbody>
<tr valign="top" align="left">

<td width="699">
<p><font style="FONT-SIZE: 10pt; FONT-FAMILY: 'Century Gothic'" color="#ff0080">Dear Madam,<br>
</font> </p>
</td>
</tr>
</tbody>
</table>
<table id="maleTbl" style="DISPLAY: none" cols="1" cellpadding="2">
<tbody>
<tr valign="top" align="left">
<td width="698">

<div align="justify"> <font style="FONT-SIZE: 10pt; FONT-FAMILY: 'Century Gothic'" color="#0080ff">Dear Sir,
</font>
<p></p></div>
</td>
</tr>
</tbody>
</table>
<table id="biTbl" style="DISPLAY: none" cols="1" cellpadding="2">
<tbody>
<tr valign="top" align="left">
<td width="698">

<div align="justify"> <font style="FONT-SIZE: 10pt; FONT-FAMILY: 'Century Gothic'" color="#0080ff">Dear Sir or Madam?,
</font>
<p></p></div>
</td>
</tr>
</tbody>
</table>

</body>

Hope that this code will help you.

If you want to thank me, follow my blog and recommend me to your friends.

Anonymous said...

Mark many many thanks for that.. it is exactly what I needed.. you have made my day.. spent hours last night trying to get my script to work like this.. but just could not do it.. soooo annoying.. went to sleep thinking about this all night.. could not get any sleep and then woke up (Sydney Australia time) and read your post.. put the code in and boom.. it worked.. Great!!! I was really pulling my hair out... Absolutely wrapped.. thanks heaps..

My next thing, is to get the submit button when pressed to go to www.1.com if male selected, www.2.com if female selected and www.3.com if bi selected.. you would not by any chance know how to do that would you?

Thanks Again from Sydney Australia

Anonymous said...

Just came across an issue.. always an issue :).. I have added a txt box in the tables for male, female and bi (changed to div's)..I am using CS4 spry validation to make sure all fields entered etc.. If they select male they must fill out the txt box, if they select female they must fill out the text box that appears in that section etc... How do I get spry just to check the txt boxes within the table/div selected?

Thanks again... I feel if I can nut this out it would have been agood weekends work..

Anonymous said...

Oh.. and just to complicate it a little further all the info submited will be inserted into a mysql db.. using the CS4 insert behaviour for that..

Nancy said...

Hi Mark - Thanks for the helpful info. I didn't like the pagebreak that "DISPLAY: block" gave me so I used "DISPLAY: inline" instead

Mark said...

Nancy thanks for tip.

Sorry Sydney, I never work with CS4 spry. I suggest you to check your div display property. If it is none don't do check if it is block do check.

Anonymous said...

Hi Mark, I used your script and it all worked perfectly in IE6 and IE7.. The page was showing/hiding as I wanted and everything was just great... then while at work I checked out the page in Google Chrome and.. it did not work.. sooo annoying.. nothing would show.. everything was hidden??? Not sure why? Any reason why the script would not work on Chrome?

Thanks again from Sydney..

Mark said...

I tried to load my blog in Google Chrome and TOC show/hide work.
Maybe javascript is disabled in your Google Chrome explorer?

Anonymous said...

Hi Mark, just tested your show/hide example in your blog in Chrome and it works perfectly... but using the code you made for me below (your last post with all the script details - cant post php html) the page does not work???? Works in IE6 and 7, and FF but just not Chrome??? Sooo annoying because otherwise the script is perfect...

Any ideas?

Mark said...

It is possible that somewhere in a script is a error. IE and Firefox ignore this error but Chrome don't.
Don't know where error is. I suggest you to try find error. You can try to make simple example of code, and then test it. If it is work, make it more complex and test it. Until you find error.

Maybe problem is in :

<script type="text/JavaScript">

line.

To post HTML you can look :
How to display HTML code in blog or web

Anonymous said...

Thanks Mark.. will have a play around with it on the weekend...

Anonymous said...

Hi Mark, had a play around on the weekend with you code.. could not get radio buttons to work in Chrome.. sooo annoying.. anyway eventually got this to work..

See below... thanks again for all your help much apperciated and great helpful posts.. PS.. I used Marks suggestion and used postable to post html/jscript code

Cheers

<script type=""text/javascript>

function display_div(hide1,hide2,hide3,hide4,hide5,show){

document.getElementById(hide1).style.display = "none";
document.getElementById(hide2).style.display = "none";
document.getElementById(hide3).style.display = "none";
document.getElementById(hide4).style.display = "none";
document.getElementById(hide5).style.display = "none";
document.getElementById(show).style.display = "";
}

</script>


</head>
<p>
|1<input type="radio" name="kind" value="" onclick="display_div('cnt_02','cnt_03','cnt_04','cnt_05','cnt_06','cnt_01')">
|2<input type="radio" name="kind" value="" onclick="display_div('cnt_01','cnt_03','cnt_04','cnt_05','cnt_06','cnt_02')">
|3<input type="radio" name="kind" value="" onclick="display_div('cnt_01','cnt_02','cnt_04','cnt_05','cnt_06','cnt_03')">
|4<input type="radio" name="kind" value="" onclick="display_div('cnt_01','cnt_02','cnt_03','cnt_05','cnt_06','cnt_04')">
|5<input type="radio" name="kind" value="" onclick="display_div('cnt_01','cnt_02','cnt_03','cnt_04','cnt_06','cnt_05')">
|6<input type="radio" name="kind" value="" onclick="display_div('cnt_01','cnt_02','cnt_03','cnt_04','cnt_05','cnt_06')">
</p>

<div id="cnt_01"style="display: none;">
CONTENT ONE
<input type="textbox" name="fieldOne" value="">
</div>

<div id="cnt_02"style="display: none;">
CONTENT TWO
<input type="textbox" name="fieldTwo" value="">
</div>

<div id="cnt_03"style="display: none;">
CONTENT THREE
<input type="textbox" name="fieldThree" value="">
</div>

<div id="cnt_04"style="display: none;">
CONTENT FOUR
<input type="textbox" name="fieldfour" value="">
</div>

<div id="cnt_05"style="display: none;">
CONTENT FIVE
<input type="textbox" name="fieldfive" value="">
</div>

<div id="cnt_06"style="display: none;">
CONTENT SIX
<input type="textbox" name="fieldsix" value="">
</div>

Mark said...

Yes it is true.
Radio button show hide really don't work with table in Google Chrome.

Anonymous said...

Hi Mark.. yeah Chrome seems to have a few weird things going on.. but still early days yet..

Anyway any chance you could help me on my next issue..

I Need a show hide feature to add more and more text boxes.. when some clicks add..

For example I want to have question..

Add pet name.. when they click it text box appears.. I can use your first show/hide script for that... but then I want an option after each text box inserted to '+Add another pet'.. when they click that another text box appears and they can add details for pet number 2.. and the option to '+Add another pet'.. so they can add pet 3 details and go on and on.. no more then 6 pets.. Would also be good if they could delete pet details.. and do it out of order as well... so 'delete Pet Details' appears near each text box.. so if they entered details for pets 1,2,3,4 they could just delete details for pet 2 and leave details for pets 1,3,4..

Sounds complex.. and is.. but would apperciate your input etc..

Thanks again

Mark said...

Hm,
you can add 6 text boxes with button "+Add another pet" and with button "Delete this"
Every text box and buttons should be in one div.
By default those 6 divs are hidden except first div.
When user click on button 1 "+Add another pet" div with textbox 2 and two button's should become visible.
When user click button 2 "delete this" div 2 should become hidden.
When user click button 3 "+Add another pet" div 4 should become visible.
And so on.

Or you can just put 6 text boxes and if user have only one pet then others 5 text boxes remains empty. Sometimes simplest solution is best.:)

Anonymous said...

Just to say thanks nice and simple tutorial very well explained

Anonymous said...

The radio button hide-and-seek trick not only doesn't work on Chrome, it doesn't work on Safari (for Windows, 3.x and 4.beta, and probably not for Mac, either). It's my understanding that Chrome and Safari share some (apparently bad) code, so that's no surprise. I've used radio buttons for this purpose on my home page (see the bottom of http://www.billanddot.com ) for a couple of years, and they've never worked on Safari for Windows. (OTOH, the hit counter on that page, courtesy of my host service, works on Chrome but not Safari.)

Mark said...

Thanx on the tip.
If you find this article useful I would be grateful to post a link to my blog.

questionbank said...

HI,
I have been scratching my head for the past 2 days over this.
Can someone help me...
This for me is working fine on a normal html page, but its not working on Blogger.. any hints...

thanks in advance..

is it that some part of this script should be placed in the head tag...
please help

Mark said...

If you have problem with javascript in blogspot post then maybe article about implementing jscript in blogger post wil help.

Kausar Ansari said...

I am beginner in javascrip and have to learn please tell me from where i got it

Mark said...

To start learning javascript my advice is to start at http://www.w3schools.com/js/default.asp

smiley said...

my head is still spinning (@.@) not familiar with coding and i'm working on too many lines to show/ hide... at least yours is the simplest so far. wish me luck. thanks :)

smiley said...

mark, i'm back because i'm down. been struggling with the codes and lose the war. can you enlighten me for a bit? few questions here:-

1) i have formatting for the link and for the text to be hidden (like bold, italics, blockquote, justified, paragraph, ul) should i put the formatting tags before or after the "a" tag?

2) for some reasons, there are few extra spaces in between my first showhide and the second showhide. the rest appear ok. any clue?

3) is there any limit in the number of id? i have up to 19 (hiddenDiv19). working good from number 1-14 only, 15-19 all hidden inside 14. checked the codes couple of times, not sure which part gone wrong.

i've removed the page so there is no reference i can give. too long to paste it here...

smiley said...

mark, figured it out! :D its the placement of my blockquote tags. oh, those blockquotes...gave me so much problems with the alignment, causing different font type on some texts, bullet list all haywire but all ok now. so much thanks!

Gary Joe said...

Thank you. That Show/Hide html code is exactly what I was looking for!

Cheers,
Gary Wolff
Tokyo, Japan
http://www.garyjwolff.com

NewKadia said...

Great script, but is there a way to have the link say "Show" when the material is hidden, and to say "Hide" when the material is visible. In this way, there's a bit more clarity for the clicker. Thanks.

Mark said...

Here is an answer for NewKadia, how to change lnik test to "Show" when the material is hidden, and to say "Hide" when the material is visible:

<script language="javascript">
function divHideShow(divToHideOrShow)
{
var link = document.getElementById("linkId1");
var div = document.getElementById(divToHideOrShow);

if (div.style.display == "block")
{

div.style.display = "none";
link.innerHTML = 'Show'
}
else
{

div.style.display = "block";
link.innerHTML = 'Hide';
}
}
</script>

<a href="javascript:divHideShow('divA');" id="linkId1">show/hide Div A</a>
<div id="divA" style="position:absolute; display: block"><h4>Div A</h4></div>

DEEPAK OBERAI said...

Hi, I Saw Your Link in Bing.com I Love Your Blogs Kindly See my Link Here a New Alternative Money Making Network  best alternatives to adsense here

Anonymous said...

GREAT

rtbite said...

this is certainly what i am looking for..thanks..

nandini said...

hi mark,

could u please extend the same topic and explain as to how can we hide other elements in a table and get them visible on the click of one of the row elements..


eg:if i have 5 elements in a row i would like to click the third element and get the rest two elements to be displayed...
would be pleased to know your reply asap..
thanx in advance

Mark said...

To nandini:
Try read Show and hide multiple divs.
You can put elements in divs. Divs can be inside table.

Anonymous said...

is there an easy way/wordprocessor to show /hide text, just simply chose and block text area where i want to hide?

Mark said...

Sorry, for wordprocessor I do not know the answer.
Maybe you can try with VBA:
http://help.lockergnome.com/office/Checkboxes-show-hide-text-word-document--ftopict858640.html

Bonafide Jones said...

Any advice on getting it centered? I've changed the alignment in the wysiwyg editor also just used the spacebar to center it myself. Both seemed to null the java script. It show the 'show/hide' but nothing happens when you click it. thanks for the help and thanks for the great script.

Mark said...

To : B. Jones
I didn't know until know centering is a problem.
Here is example solution:
- put HTML element you want to center in the div element
- in style of div element margin-left and margin-right attributes should be set to auto

Example:
<div style='width: 300px; margin-left: auto; margin-right: auto;'>
AAA
</div>

This should center content of your div element!

shan said...

hi,

i am writing a document where on the click of radio buttons div are swapped but the problem is that if button for div-2 is selected and i do a refresh then in selected buttons remains same but the div shown changes to div-1.
Is there anyway on refresh also the selected div is shown if not at least everytym i refresh div-1 is automatically selected

Mark said...

To Shan:
Sorry Shan I do not understand.

Anonymous said...

Hi Mark,

I'm having the same problem as Shan.

If you select Option A, B or C on the page here and then refresh the page the option stays selected but the DIV is hidden becomes hidden.

Thanks

Mark said...

Hello,
Unfortunately, I do not know exactly how option value is preserved after refresh on blogger.
DIV is showed after function show() is called.
After this page is refreshed function show() is not called, just option value is preserved.
If you want to manipulate with showing and hiding after refresh I suggest you to try to check which option is clicked inside body onload event.
Find more about body onload event here:
http://www.w3schools.com/jsref/event_body_onload.asp

E & C Products said...

Thanks this is very usefull, but the radio vit doesn't wark for me

Mark said...

To C Products:
What exactly does not work?

Anonymous said...

it does not work on chrome?

Anonymous said...

Got it! Found the chrome solution among the comments. Thanks.

Jack said...

example with textbox. when i focus on it, i wanna show my div...

Anonymous said...

hi.how can i use show/hide html JavaScript.when i want to show hidden text on some other page ???

Anonymous said...

hello how can I make the script wait 10 seconds before displaying the div text

cardiologyreview said...

WOW NICE BLOG STUMBLES ACROSS YOUR BLOG!!!. Thank you so much. I have taken the liberty to use your codes on my blog.

I have a question though? How do i insert a picture to the reveal the hidden answer code?

Many thanks, god bless you.

Shan Khan said...

Its not working in Google Chrome.. Can anybody help ???

Anonymous said...

Awesome thanks!!!

oweceej said...

Thank you for this post, it was a big help to me.

Michael Jay said...

is there way to see past the html?

Prathiparaj P said...

Thanks

Muthu Kumar said...

It woking fine Thank you so much