Using javascript to hide and unhide elements dynamically
My favorite aspect of javascript is that it enables you to add great features to your site like showing/hiding parts of it when a user clicks a link without reloading, get some data from a database and displaying it in a new div, again without reloading. In fact, it would be possible (although not very comfortable and easily codeable) to create a big website, like a WordPress blog without any reloading at all, no matter where you click.
This is usually referred to as AJAX, although most of it is javascript and HTML, and it is actually easier than it seems. In my opinion calling the hiding and showing of elements is not yet AJAX, because in my eyes ture AJAX communicates with the server in the background. We will only be changing CSS properties and element contents with javascript in this post to achieve our goal.
Let's say you're creating a form, and you want a way to explain what the fields do or what data they need to contain, but you don't want to fill up too much space on screen, and you want to make it as unobtrusive as possible. In this case it would be cool to have a link with the anchortext "Explain", which would expand a section which explains what the user needs to do.
As the first step, we need to create a div which will hold the explanation text, and a link which will unhide it for the user.
<a id="link1" href="javascript:display('show', 1)">Explain</a>
<div id="explanation1" style="display:none">This form let's you input your order details, please keep it short!</div>
As you can see I have given the div a unique identifier. This is needed so the javascript knows which div I want to change. I have added a number to the id because there might be many more explanations, these would receive different numbers. I have also given the link an id, with the same number at the end as the div. Once the user clicked the link, we want to change the link, so clicking it again will close the div.
The link contains "javascript:", which indicates that this link doesn't point to a page, but should execute javascript code, in our case a function (display), with two arguments. The first tells the javascript function which will execute that we want to show the div (as opposed to hiding it), the second is a numerical identifier, which should be the same as the number in the div's id. Take a look at the javascript code below with the explanation afterwards.
<script type="text/javascript">
function display(action, id)
{
if (action == 'show')
{
document.getElementById("explanation"+id).style.display = "block";
document.getElementById("link"+id).href= "javascript:display('hide', "+id+")";
document.getElementById("link"+id).innerHTML = "Close";
}
if (action == 'hide')
{
document.getElementById("explanation"+id).style.display = "none";
document.getElementById("link"+id).href= "javascript:display('show', "+id+")";
document.getElementById("link"+id).innerHTML = "Explain";
}
}
</script>
As you can see, the two arguments are named "action" and "id". The action argument will tell the script what we want to do (close the div or show it), the id argument will tell it which element we want to do it with. When you first click on the link the action is "show", so let's take a look at what's happening there.
First of all, the script checks what the action is. It sees that it is "show", so it executes three lines. the first line sets the div's dispaly to block, which means that it will appear, you will be able to read the text. this is achieved by "grabbing" the element using its unique id. By specifying "document.getElementById('theidhere')" you can grab any element. In our case, we always grab the element "explanationX", where X is the number beside it, given by the id argument. This id argument makes it possible to use one function for all the divs you want to open or close, so we won't need to code the same function for all the different ids out there. The bit of code following specifies that we want to change the style, more specifically the display property, and we want to change it to "block".
The second line grabs the link element, and instead of changing the style, it changes the address it points to (href), which in our case will be a new piece of javascript code. We change it to the exact same code, but instead of "show" as the action, we now have hide.
Line 3 grabs the same link element, but now changes the element contents. An element's contents is always whatever is between the start and end tag, in a link's case this is the anchor text. We change it from "Explain" to "Close" so the user knows that the div will disappear if he clicks the link again.
The three lines in case the action is "hide" do the exact same things, but change the values back, so if the user wants to open the div again he can do so.
That wasn't so hard was it? The uses for these javascript methods are truly endless, from checking registration forms before submitting, to dynamically adding text to your site, you can do almost anything here, your imagination is truly the limit, so have fun!
Advertisement
Thanks
It’s perfect!
Huge thanks man, I was looking for this for ages.
wow! this is an awesome example
Hi!
Thanks for this script. I’m trying to twist things around a little- how would the script read to have multiple DIVS hide and show with one click?
Very Nice. Thanks a lot friend.
Really good one! Thanks a lot…
This was super useful – thanks
This would be a good tutorial, but you left half of it out. It’s obvious to me that your neglect in putting in html code examples makes it all but useless to the novice. Being fairly experienced I figured out how to do it on my own, but I expect most people will not be able to do that so easily.
If you’re going to take the time to do something, take the time to do it right. Otherwise, don’t bother!
Please let me know when you correct this very substandard article!
Following on from the FAQ example, how would you change the JS so that you could make the page display the riginal text for the link when you close it, rather than “Explain” (or any other standard text)…as each question would presumably have a different text displayed…?
Thanks
Excellent! Very very useful! Thank you!
thx! i found what i want here
Fantastic. Exactly what I needed.
Awesome! I’m just learning HTML and CSS now, and will get into JS soon enough, but this will be a big help on what I wanted to do. (:
~Phao Loo: 90 KiB? Huh, uncompressed version…
But compressed not as big as the biggest one.
What’s a problem selecting a part of code which manages event binding? jQ is modular. ;)
Hi jurkis!
Try something like this (use the same js as I have in the post):
<a id=”link1″ href=”javascript:display(‘show’, 1)”>Question goes here</a>
<div id=”explanation1″ style=”display:none”>Explanation goes here</div>
For the secod question you would have:
<a id=”link2″ href=”javascript:display(‘show’, 2)”>Question goes here</a>
<div id=”explanation2″ style=”display:none”>Explanation goes here</div>
Let’s say i have a FAQ page.
How to make this script to open/close Answer by clicking on Question?
Sorry for my english.
Maybe you could make a subdomain, say tutorials.ghacks.net with an index for grouping these lessons?
That’s an interesting idea Jojo. I think about it.
Nice tips, I like thÃ.
@eRIZ: instead of using more than 90kb for jQuery for this, just use this code.
Hi eRIZ!
I did not know that javascript pseudoprotocol was not the best solution, I’ll switch, thanks :) We live and learn!
err: onclick instead of click; I’ve been working too long with jQuery. ;)
Hey, dude, WT… “javascript”?
Have you ever heard about unobtrusive event binding?
var l = document.getElementById('ident');
l.click = function(){ alert('wassup?!'); return false; }
javascript pseudoprotocol is bad and not semantic…
I always find this thing to be very annoying on while writing my blog. I type & sign but when I login some time later I find it has changed to &, anybody knows why?
No problem gB :) For the same reason you can’t really copy paste link codes and stuff from Word documents unless you do some preparation first :(
Pretty easy to find & replace, but still a bother.
Wow thanks for the fast response. Fixed the quotes like you said and now it works like a charm.
Awesome
Happy I could help :) There are loads of other ways to do this, I’ll get to them later. If you put a lot of content in hidden divs it’s actually better to pull the content from another page or db, since then you don’t need to load all of it initally, just the ones visible :)
More on this later :)
well that was fun – using this technique I managed to put all a (small) site’s content on one page, and use the hiding/unhiding of sections to simulate pagination. Cut down on a hell of a lot of work for me, so thanks again Daniel!
Thanks Daniel, keep these tutorials coming!! they are very useful :)
and as Paul suggested i too wish for the same, i.e. pdf edition. Thanks. :)
Hi guys!
Thanks for the praise, I’ll keep ’em coming :)
Hi gB!
I should have written about this before, what you need to do is replace ALL the quotes in what you copy pasted with actual quotes. They appear as these weird slanted things in the post, there should always be simple ‘ and ” whenever you see single or duoble quotes.
I will try and work out something where you can copy-paste!
Hi Paul!
Right now I don’t really have time to compile something like that, but if these articles are successful I will think about it :)
Thanks again for the praise and this is such a great method, I really do love it so, please use it :)
Hoi Daniel great read again. Is it possible that you make every mounth a .PDF, with that mounth artikels?
Sorry can’t find a way to edit my comment. Just wanted to also add excellent work on the php and now js articles. Keep’em coming.
I’m new to javascript so I could very well be missing something. But I’ve copied and pasted (actual Ctrl C and Ctrl V) this code into a basic html file so I could see it action, and clicking on the Explain link does nothing. I’ve tried putting the part both in the head and body and nada. Any clue on a reason why?
I concur, I’ve just refreshed my basic web design (CSS & HTML) and I’d love to learn some Javascript without just cut/pasting from code snippets.
Lurn me good, gHacks!
AJAX, JS, PHP seems to be very useful. Thankfully most websites use them. I use to hate those slow html things to load up. For every stupid click they used to download the entire page again. I learned basic HTML …. thing few days ago, cant wait to learn php.
PS: Daniel, why don’t you upload images to describe your point?
More tutorials please! This one is very good.