<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
Inline usage:
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>
What is this? … Looks like it was scratched off a bathroom wall somewhere…
Where’s the function statement? And how about using var for declaring local variables?
I think it was a bad copy and paste job compounded. Fixed it up a bit.
Thanks for fixing it Chris. :)
Sorry to comment on an old thread Chris, but this worked perfectly for me! Your website is extremely helpful and much appreciated!
Thanks Chris!
Just wondering as a new person to JS, is it better to apply the function inline as shown in the example above by Chris or is there another way to return the function not directly inline? Thanks!
the only problem i have with it is what i have to click the link twice the first time to make it disappear.
Why does this need 2 clicks? I’m new at javascript, and this is driving me crazy!
change
<div id="foo">This is foo</div>
to
<div id="foo" style="display:none;">
Start with ‘none’ instead of ‘block’, then you don´t have to click twice first.
This function works better!
function toggle_visibility(id) {
var e = document.getElementById(id);
e.style.display = ((e.style.display!='none') ? 'none' : 'block');
}
Hi!
Thanks for this snippetand the comments.
I am new of javascript, I changed the label link to “Show”.
It is possible toggle the label between show and close ?
Thank for the attention
Voreno
I feel that the usage of display:none should be avoided if that is possible. Some versions of Webkit based browsers consider display:none like the element no longer a part of the DOM.
Instead you can have a CSS class like the following one:
.hidden{
position: absolute;
left: -9999px;
top: -9999px;
visibility: hidden;
}
After using JavaScript code you can add or remove the class name if you wish to hide or show the element respectively.
The advantage is the element will be present in the DOM all the time but in a non-visible manner if it is in hidden state.
Very useful code snippet. Has been very useful to me. Keep up the good work
@Jayaprakash – This is the most correct method outlined here.
@Escrimador
As an old code hand you should remember the 3 layers of separation principle?
Use JS to toggle (interaction) a class and let CSS to do the visual work.
Personally I like to keep overrides as simple as possible:
.hide {
position: absolute;
left: -200em;
}
Note the use of ems which pushes the content further off-screen the more the font-size is increased by the user.
Works most of the time but sometimes you may need:
.hide {
position: absolute;
left: -200em;
width:0;
height:0;
overflow:hidden;
}
But that’d be rare and it’s best to use the minimum version until it fails.
nice but i do believe screen readers will still see the content in the .hidden, which would be sub-optimal for the sight impaired.
Correct me if i err.
hai sir,
function toggle_visibility(id) {
var e = document.getElementById(id);
e.style.display = ((e.style.display!=’none’) ? ‘none’ : ‘block’);
}
one
two
three
if i click all the three controls means div content overrided (merge in same content).how can i neglect that.
This is great, thanks for your Support!
So when did display:none get deprecated? Do you even know the difference between visibility:hidden and display:none Jayaprakash?
Now I’ve been a css developer since pre css days back in 1995 now almost 11 years as a Sr. UI Engineer and to this day many so-called css folks can’t even answer the simple question.
Please if you’re giving css assistance, please be correct! Now do you even know when to use position:absolute and how to make it move with the “parent” elements when the browser resizes? Geez Louise…lmfao!!!
Pretty obvious you don’t know css coding. Matter of fact display:none still exists in css3 along with all the other new pseudo classes.
You were a css developer before css was introduced?
I would bow to your superior knowledge, but I use the internet without using the internet.
@Escrimador are you just rude by nature or do you have to try at it? @Jayaprakash was simply pointing out that sometimes you want to hide an element but don’t want it disapearing from the DOM as that means your javascript program loses sight of it to.
visibility:hidden leaves a space where the item was, whereas display:none closes the gap so you can’t tell there’s a missing element in the layout.
I don’t think it was necessary to sound quite so condescending in order to answer a simple question. After a decade in the industry, you should know better than to act that way.
Your big “stumper” that no one knows is pretty damned simple. visibility:hidden leaves the item in place but renders it invisible. display:none completely removes it. Not really that complicated, I’m pretty sure more people know this then you give credit for.
Your entire post gives absolutely no information, it just makes you look like you need to prove yourself to someone. If you are going to criticize someone’s help, why not try to actually be helpful?
And if you need help with your third paragraph, I suggest you look up inheritance and nesting. The latter more than the former.
Okay Pu, let me tell you something that Jayaprakash didn’t tell you because he is not a qualified css person.
The difference between visibility:hidden is that although it is not visible on the web page, it still takes up space. Meaning, it the hidden element is say 500px wide by 500px high and in the middle of the page between lets just say a header and footer element, there will “ALWAYS BE A 500X500 EMPTY SPACE THAT’S VISIBLE ON THE WEB PAGE WHEN VISIBILITY:HIDDEN IS USED.”
With display:none, with say the same elements a header and footer with an element in between set to display:none, there will be no visible and “UNWANTED WHITE SPACE VIEWABLE ON THE WEB PAGE” unless/until a call to action is made via javascript/jQuery or css. The same effect you get with drop-down menus and accordions.
Be careful with the answers you read on blogs. It really infuriates me that some people are so loose with their answers and obviously don’t know what in the world they are talking about.
Says the man who claims he was developing css before css was introduced.
@Escrimador, the class called hidden that @Jayaprakash suggested positions the element as absolute meaning it is removed from the flow. The left: -9999px and top: -9999px then moves it way off page. So once again you are wrong.
.hidden{
position: absolute;
left: -9999px;
top: -9999px;
visibility: hidden;
}
@Escrimador – HA HA HA at you claiming to have worked with CSS before CSS was even around. Additional HA HA HA for you being so up to par on your CSS that you didn’t even know that the negative set values for top and left remove the element from the page, thus removing any chance of seeing white-space (which was the basis of your argument). I guess you needed to practice more with your CSS huh? I would figure you would have spotted that with your 10+ years of experience.
He was right about one thing, even though his post was from 2011. You should be leery of blog posts because you may encounter an idiot like him who is a self-proclaimed expert yet failed to realize that the negative insertion removed the element, which even THIS novice knew. HA!
WOW! @Escrimador,
I know I’m way late to this story BUT, I use both depending on the need. When using SVG images I might use ‘visibility:hidden’ cause it’s an image within the DOM and things don’t move NOR do I want to take the chance a browser tries to make them move, so error on the side of caution.
Other times say data is coming in from an outside source IN TO an image map, yep working with images again. But this time when the data says that element is not here then I use ‘display:none’ to remove it from the page entirely.
So help me understand, where was I rude in my outline of my use and why could you not be more the same and not such, well what you are.. (we need less of ‘you types’ in this world)
The reaction to Jayaprakash was way out of line folks.
He never actually said that display none was deprecated. There is really no reason to attack him personally.
He simply said that some browsers handle it differently…. “Some versions of Webkit based browsers consider display:none like the element no longer [is] a part of the DOM”
If this is true, it might explain some odd behavior I’ve seen. I sure would like to know definitively.
I am using this method for faq’s where each answer is hidden by default and only shown when a question is clicked. Is there any way to target a specific question with a url and anchor that when visiting the link, it will scroll do that question and that answer will expanded by default?
Thanks!
Hey hi Chris, I used jquery many times for toggle, in one my clients site this time I used CSS3 for toggle using :target. It really worked so I wrote a tutorial on it, sharing it here :)
http://webstutorial.com/html5-css3-toggle-slideup-slidedown/html-5
@Dillon @Drew that double cliking issue got me some problems too, but i’ve found a solution thanks to this post.
In few words, the first click fires the if part of the function and ask “is the element display property set to block?” and the function terminate “prematurely” (so to speak) since it checks correctly that query. The second click put the script on work, since it has already checked the if requirement with the first click.
So you have to sort-of “cheat” the script asking logic:
With this only 1 click is needed, since it asks “is the element display property set to none?”, the function check that is not correct, and pass directly to the else part setting the desired effect!
Hope this is somehow understandable, english is not my first language ;)
Cheers!
one question how can i implement that in various divs.
And thaks for sharing.
thanks i already found out how.
I was wondering weather ther is a way of hiding the Content in the Div and opening it by clicking the anchor,rather than haveing it opne at the beginning and needing to click it tio close. So basically the oposite of the current script. thanks in advance.
Great post Chris! Max, I was able to attain the results you prescribed by simply adding a
display:none
declaration to the element I am applying the script to.You then have to be sure the script is written as it is in Chris’s original post, where the script’s initial click displays the block, as such:
This will ensure that the element is not displayed when the page is loaded and only requires a single click to toggle it on.
in using the show or hide element, i put two elements in the same div. what i want to do is hide one when the other is showing. this is because when one element is shown and the other is also revealed, the later one is superimposed on the older one. i would like only the new one to show. how can i do this?
Hey, thanks for this!
I have an issue where the div is indeed showing and hiding as desired, but where I’m being taken to the top of page each time I click on the toggle. This is true in both FF and chrome. Any ideas?
Thanks!
Hey Alex,
That’s probably because the anchor target in the example is “#”, which’ll jump you to the top of the page because the browser is looking for an ID with no name. A link with a target of “#header” would likewise jump you to the element with the “header” ID!
Using a span with an onclick event should let you drop the target entirely:
<span onclick="toggle_visibility('foo');">Click me</span>
Really cool all around useful bit of code but I’d like to remove or hide the “Read More …” button once it’s clicked and the initially hidden content is now displayed.
Thanks a lot ! very useful !
I changed the code to to what it is below and it works perfectly fine. But one thing I am not too sure about is how to get an image to show up for both states, i want to use Expand and Collapse and it is not working. I am not a JS developer, I know HTML and CSS very well but not JS so much, I can understand it but I cant write it per se. Any ideas?
I am curious, can anyone explain how to code so that when a toggle is opened the display shows the top of the toggles content?
Whenever I use toggles with lengthy text in them, I have the problem where upon opening them, the screen shows the information from the bottom of the toggle field and not the top.
I’d love to change that. Thanks for any help.
I’m having an issue in IE 9 (of all things) when using this toggle. I’m using it to toggle a nav and IE 9 actually eats my list items when this script is in place. Anyone had a similar issue or solution? Here’s my markup:
I can’t seem to make these functions work if the webpage has BOTH 1) a display: block div that must be triggered to hide and 2) a display: none div that must be triggered to appear. Reversing the logic of the function will either require 2 clicks to show and 1 click to hide, or 2 clicks to hide and 1 click to show. How can this function be written properly to apply to both situations with only 1 click?
Hello WordPress what is the problem of this site – http://theblackcheese.org/category/blog/
why post are not visible and the category post are not visible all post are not visible please help me.
Best Regards,
Abner
This script is excellent! Thanks for sharing. The one issue I am having is a way to properly ‘hide’ other div’s that were revealed by other click events. I have two buttons that I want to use this script on, but I need to have the content revealed by one button closed when I click the other button.
I am not sure if this is making any sense. I just don’t want two sets of information revealed at the same time. Thanks for all your help in advance!
Hi, I have read that Search Engines like Google ignores Javascript. So if I use this code to place text inside the toggle will it be ignored or will Google crawl the text?
A quick reply on this will be really helpful.
thank you……
Hi,
I have text links that all use “onClick Show/Hide”, but I would like for another image to be present in that space ‘before’ clicking on the links.
Also I would like the ‘current’ text link to be bold until the next link is clicked on.
I think this is probably an easy solution for all of you. Can anyone help? Thanks in advance. :)
What I have: http://thispixelstudios.com/working/scottsdaleranch/index_test.html
Example of what I want (vertical 4 link section): http://www.drsrtc.com/
Thanks guys, somehow I managed to end up on CSS Tricks again after hopelessly reading about how to implement such a simple snippet on at least 5 different discussion boards around the web.
I particularly want to point out other googlers to Steph’s < span > usage to avoid sending the user to the top of the page.
Thanks again!
This script works really well, thanks.
But is there any way to add a little animation to it so it’s a little more smooth?
This has been working well:
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/
Great, clear, brief!
Any suggestions for adding transitions/animations to this?
CSS transitions don’t work with the display property as far as I know.
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == ‘block’) {
//Set opacity to zero, with a CSS transition-duration of 0.3s
e.style.opacity = ‘0’;
//Set timeout of 300 ms (or the transition-duration of your CSS) to remove the element from the flow
setTimeout(function(){
e.style.display = ‘none’;
}, 300)
} else {
//Immediately put the element back into the flow
e.style.display = ‘block’;
//Now set the element’s opacity to 1, which will be done nicely with CSS-transitions
e.style.opacity = ‘1’;
}
}
And you’re done ;)
HAHAHA – You guys are shitting me right? Please, continue as this is very entertaining. You guys are arguing over some snippets of code. You are all worse than a bunch of 14 year old girls arguing over Justin Bieber music lol…
Great script and it doesn’t clash with the jQuery that was already being used on my page! Thanks
I used this one for small project. But imo add/remove class is far better.
Instead of using visibility:hidden, use display:none; so this by default hide you’r element, and create such animation that can slideToggle or just show and hide by making click event..
Hi! I have implemented this function but the problem is that when the hidden element appears ,the rest of the page does not move down. So the element appears over the rest of the page. Is there any way to avoid this? Thank you!
Hi, thanks for the handy code, it didn’t quite work for me in Chrome though- I had the 2 click problem. The reason is that starting with my div style set to display:none meant that e.style.display was an empty string ”, and not ‘none’. So the way to avoid the 2 clicks problem is to test that the string is NOT equal to ‘block’, which treats both ‘none’ and ” in the same way:
Hi,
Thanks alot all for sharing great stuff.
I did everything you people showed which works great.
I have a question.
What if I want to link the hidden divs from another page so that when I click on that link it will open the specific div and keep the rest closed.
Thanks alot.
It can be done even simpler with JavaScript. CSS3 provides such feature, you can use the checkbox trick, here is example, it’s also simple as you JS: creating a toggle box to collapse or expand content using only CSS3
The function is great but how to use it in a table?
<div>
does not work well in table. What I have is a bunch of links in the table cells, and all of them are in class “page”:<table> <a href="visible1.html" rel="nofollow">visible page 1</a> <a href="visible2.html" rel="nofollow">visible page 2</a> <a href="test1.html" rel="nofollow">test1</a> <a href="test2.html" rel="nofollow">test2</a> <a href="test2.html" rel="nofollow">test3</a>
How to code the javascript function to show/hide the links? Thanks!
some modifed >
javascript:
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none'){
e.style.display = 'block';
}else{
e.style.display = 'none';
}
}
//-->
</script>
html:
<input type="button" value="show" onclick="toggle_visibility('test');">
<div style="display:none;" id="test">div contents</div>
nice, but you could animate it:
and add some style
to a menu :)
Hello, how can I use this show hide to few elements? I want to have 3 ‘foo’ with the same id, no matter which one I click, I show/hide all of them. How can I edit this code?
Tom, to be knowledge, it doesn’t works that way to have multiple items with same id. My solutions would be doing something like
JS function to accept a var of string with separator character like comma “,”
in element onClick="toggleMultiple('foo1,foo2,foo3');"
Hope it helps.
Hi
how would you use this that if you have multiple Div’s the one you click shows on screen and other Divs hide?
Mak,
not very clear of your question, perhaps you may refer to code I suggested on tom. Could that be something you wish to do?
it’s working but how to hide click button and how to change the button of click time
Holy crap this little nugget totally helped me out of a jam. THANKS CHRIS!!!
you’re a genius!
Didn’t work when I tried it in jsfiddle. Weird…
Hello
Please how can i hide a DIV when the user clicks outside of it
Thanks
In what way do i change the code if i want the div to start hidden and then shown on click? :)
Thanks
Thank you! I’m extremely new to web development and know NOTHING about Javascript. If I look at it long enough I can figure out what it does, so this little chunk of code was perfect for what I wanted to do :)
Please I am new to JavaScript. I need a script that will toggle multiple div. That is when I click on one the others closes without having to click on it again. Below is what I have developed But it requires me to click again before it closes.
Function clicmHandler (id ){
Var e =document. getElementById(id );
If (e.style.display ==’block’ ){
e.style.display = ‘none ‘;
else
e.style.display =’block’;
}
}
Looking for exactly same thing!
Anyone got any answers??
How to hide/display different elements using same id. Like different sections of a blog
you can use it may it will helps you-
http://findnerd.com/list/view/How-to-open-and-close-div-using-css/462/
Is there anyway to have 2 different links?
Hide images (when images are shown)
Show Images (when images are hidden)
Works like a charm!! :)
I´m kind of a learner with coding, how do I initiate slideToggle effect to this?
Thanks!
it is working perfect dude!awesome.
I have been working a little with this toggle thing to make a one page site with three different languages. I wanted all three translations on the same page so I did not have to write several html documents. I came up with the following;
JavaScript:
And the text examples:
Mr.L. Hansen, This is great .Iliked it. want to know why unicode of native Indian languages are not displayed though saved in Encode in UTF-8.Please guide me.Thanks.
What happens when you toggle an element that should not have block level positioning? You are forcing all elements running through this function to toggle between block or none display value. What if it an inline element or is set to inline-block?
function toggle_visibility($elm) {
};
I use this logic but with jQuery, obviously the vanilla solution of is(‘:visible’) would be much more verbose.
This will allow you to retain the original position property of the browser DOM. My apologies if this was already covered.
Can somebody please let me know how I can make the text start hidden?
Hi, try my code in the comment below…
Thanks a lot! Simple, short and sweet! (= I’ve done it the opposite way…Hide the text first, and then it will be displayed when clicked.
Here’s the code:
Don’t know how I can thank you! Your code is exactly what I’d looking for!
THANK YOU!!!!!
Hey! I wanted to thank you for this! There were so many hits on google for so many very complicated devices to show/hide a
<
div> that I didn’t think I would find something that was worth it and worked so smoothly. Awesome, simple, and straight to the point.
this is very nice example to toggle
it useful code which is very easy to understand
thank you
Is there a way to make the link disappear once it’s been clicked on?
So, there’s a link that says “click to read more” or something like that. When you click on it, the div appears (which I’ve been able to achieve already by including the display:none; tag) and at the same time the div appears, the “click to read more” link disappears
@James I did a pen which might be of use. The tiny script replaces the text you click on by changing the display style and that of a hidden div which can have any amount of content. It is not a toggle.
simple and works! great job, thanks!
I am trying to get the element to be hidden initially then show when clicked. I have tried using display: none; or visibility: hidden; but that just makes it not show up at all even when the button is clicked. I have also tried adjusting the original codes style display to mirror the opposite as someone suggested in a prior comment but nothing happened.
Does anyone have any other suggestions or fixes on how to get the element to be hidden then show on the click?
Hi!
I’m adapting a simple slider script i found and works perfect. Using display none for each < li > and display block for the target < li > i can link each image separately from another page. The problem is that this target image keeps visible when using the slider, i think there´s a part of the script missing for this use. I have hours breaking my head trying to find the way but i think is far from my posibilities. I would appreciate any help.
This is the slider:
http://codepen.io/danielillo/pen/WGQkzk
And this is the link for the “calling” page to the images:
https://dl.dropboxusercontent.com/u/74509233/TEMP/CALLLIST2.html
Thanks
Hi!
I’m adapting a simple slider script i found and works perfect. Using display none for each < li > and a class with display block for the target < li > i can link each image separately from another page. But when i play the slider after clicking, the next button goes to the first image and the prev button goes to the last. I would like the slider continues from the clicked image. Any solution?
This is the slider:
http://codepen.io/danielillo/pen/WGQkzk
And this is the link for the “calling” page to the images:
https://dl.dropboxusercontent.com/u/74509233/TEMP/CALLLIST3.html
Thanks
It is Good thank you for your support
Thanks @JJ…
your script was the only one that I was able to make work correctly. This hides the element and displays it on click correctly (as requested by so many here).
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
}
</script>
AND the HTML that needed to be updated:
<a href="#bar" name="bar" onclick="toggle_visibility('foo');">Read more...</a>
<div id="foo" style="display:none;">Show this FOO.</div>
I far from a JS expert… but can anyone modify this script to add a little animation? Something like a smooth slider?
Thanks!
S
hi
actually if we if we take login and signup forms side by side then if we click on login form the sign up from should be invisible and the login form should be visible
I like this toggle, but how can i get it to just replace a text block? I have bio for staff that i want to toggle/replace as different photos are clicked. tight now it just adds the bio under the previous clicked. Thanks!
hi sir and me am new in java script , so i need to ask you how to build toggle button will hide div when i run my web page and also when i click on then show the div?
Hi, That was just for one hide and show, I have used it in multiples and its working fine but how to hide all accept the clicked one(current)
You have to generate unique id’s for each div when the page is displayed. I did it for an application I built and maintain.
Thanks Mr:Chris Coyier,I found this code very much working and I think this is the simplest solution for this
Using style=”display:none;” within the div tag worked for me, avoiding the double click issue like Someone recommended in August 2013. I wanted to hide first and show later with a single click, not double.
<div id="foo" style="display:none;">
Without being a CSS specialist, I suspect it has to do with the different Cascading Style Sheet levels.
Many thanks to all.
If I created a button on HTML and I want that it will be hidden and appear only when the function says.
how I do it?
can you tell us how to hide a first div you clicked on when clicking on a second div just showed
thank you
How do you hide a div but show another one, the solutions here are for hiding only one. Can someone please post code that can solve the real issue. I have multiple divs and I want to display one at a time as the rest are hidden. Simply put, I click another button and only the div linked to it is displayed while the others disappear
It was not working in chrome with if else condition. I replaced if else with ternary operator and now it’s working fine.
how to make it work for two buttons?
It does work! But I have another problem that is it only works for the first time. When I click it another time, it doesn’t work and I have to refresh the website. I’m a beginner, so can anyone help me with my problem please? Thank you very for your help.