Switching content (javascript)

About this page

First look at the html. You'll see that there are three stories just one after the other in the code (divs called 'one', 'two' and 'three').

Onclick one of those divs will be shown (display : block) while the other two will be hidden (display : none). The 'for' loop in the javascript starts with an 'if' statement that checks to see if the div we want to change actually exists on the page. It starts off with only #one visible due to the last line of the javascript which calls the function on load with the variable 'div' being 'one'.

So, two divs are hidden and one is shown. Simple enough.

If javascript is disabled, the user will still be able to view all of the content as nothing is hidden by the css.

Small problem

I found that, although everything seems great here (or at least I think so), it's not perfect.

On some other pages, I have/had the code boxes at the bottom floated left and right so they're next to each other. I tried that here too, but when the content was switched, the floated content stayed where it was. "Hmmm..." I thought.

Country profile: Japan

FACTS

* Population: 127.8 million (UN, 2004)
* Capital: Tokyo
* Area: 377,864 sq km (145,894 sq miles)
* Major language: Japanese
* Major religions: Shintoism, Buddhism
* Life expectancy: 78 years (men), 85 years (women) (UN)
* Monetary unit: yen
* Main exports: Vehicles, computer parts, chemicals, scientific instruments and watches
* GNI per capita: US $34,510 (World Bank, 2003)
* Internet domain: .jp
* International dialling code: +81

Footer goes here
HTML
<h1>Switching content (javascript)</h1>
<div id="switchcontent">
<div class="headfoot">

<ul id="switches">
<li><a href="javascript:void[0];" onclick="switch1('one');">story one</a></li>
<li><a href="javascript:void[0];" onclick="switch1('two');">story two</a></li>
<li><a href="javascript:void[0];" onclick="switch1('three');">story three</a></li>
</ul>

</div>
<div id="one">
<h2>About this page</h2>
<p>First look at the html. You'll see that there are three stories just one after the other in the code (divs called 'one', 'two' and 'three'). </p>
<p>Onclick one of those divs will be shown (display : block) while the other two will be hidden (display : none). The 'for' loop in the javascript starts with an 'if' statement that checks to see if the div we want to change actually exists on the page. It starts off with only #one visible due to the last line of the javascript which calls the function on load with the variable 'div' being 'one'. </p>
<p>So, two divs are hidden and one is shown. Simple enough.</p>
<p>If javascript is disabled, the user will still be able to view all of the content as nothing is hidden by the css. </p>
</div>

<div id="two">
<h2>Small problem</h2>
<p>I found that, although everything seems great here (or at least I think so), it's not perfect.</p>
<p>On some other pages, I have/had the code boxes at the bottom floated left and right so they're next to each other.
I tried that here too, but when the content was switched, the floated content stayed where it was. "Hmmm..."
I thought.</p>
</div>

<div id="three">
<h2>Country profile: Japan</h2>
<p>FACTS</p>
<p> * Population: 127.8 million (UN, 2004)<br />
* Capital: Tokyo<br />
* Area: 377,864 sq km (145,894 sq miles)<br />
* Major language: Japanese<br />
* Major religions: Shintoism, Buddhism<br />
* Life expectancy: 78 years (men), 85 years (women) (UN)<br />
* Monetary unit: yen<br />
* Main exports: Vehicles, computer parts, chemicals, scientific instruments
and watches<br />
* GNI per capita: US $34,510 (World Bank, 2003)<br />
* Internet domain: .jp<br />
* International dialling code: +81</p>
</div>
<div class="headfoot">Footer goes here</div>
</div>
<div class="clear"></div>
CSS
#switchcontent {
border:1px solid purple;
}
#switchcontent div {
color:purple; padding:10px;
}
div.headfoot {
height:30px;
padding:0;
background-color: yellow;
color:red;
text-align:center;
border:1px solid purple;
border-left:0;
border-right:0;
}
#switchcontent a {
cursor:pointer;
}
#switchcontent li:hover {
color:red;
}
#switches {
width:400px;
margin:auto;
text-align:center;}
ul#switches li {
padding:0 20px;
float:left;
width:90px;
}
Javascript
function switch1(div) {
var option=['one','two','three'];
for(var i=0; i<option.length; i++) {
if (document.getElementById(option[i])) {
obj=document.getElementById(option[i]);
obj.style.display=(option[i]==div)? "block" : "none";
}
}
}

window.onload=function () {switch1('one');}

Comments

#1
2005-01-08 Anonymous says :

#2
2005-01-08 BonRouge says :

OK - quick answer.
You can either
a. Put it in your head like this :
<script type="text/javascript">
the javascript goes here
</script>

or
b. Put it in an external .js file (just use Notepad or Dreamweaver and save the file as file.js) and link to it like this (in the head of your page) :
<script type="text/javascript" src="file.js"> </script>
I think maybe I've been overestimating the average web designer. I thought the average person interested in putting this kind of code in their page would know where it went. My mistake. When I have some time I'll add more basic stuff to the site (or maybe just a link to w3schools).

Another point here is that I thought that it would be a nice thing to not make people sign in to the site - you know, become a member and get a password and stuff like that. I thought it would be OK to just let people leave messages. The user who left this (the first comment on the site) didn't even bother to leave a name. It would be nice to know who I'm talking to - even if the name isn't real.

#3
2005-01-10 Anonymous says :

#4
2005-01-10 BonRouge says :

D'oh!
I thought I'd fixed it now so that you'd have to leave a name.
I've tried again and hopefully it'll work next time.
Anyway, I hope you found the code useful. I do appreciate the feedback.

#5
2005-02-09 Siddan says :

#6
2005-02-10 Siddan says :

Ahh ok nevermind. I just copied and pasted the js source again and works fine

#7
2005-02-10 BonRouge says :

It's true that id's shouldn't start with a number - that's why I used "one", "two" and "three" instead of "1", "2" and "3".

Anyway, I'm glad you found this useful.

#8
2005-06-15 Shannon says :

This is great! How can I make the links update MORE THAN ONE div? When I hit the link, I want it to update 4 different divs on the page (for translating different areas of the page into four different languages). Thanks a lot!

#9
2005-06-16 BonRouge says :

Hi Shannon,
Do you mean something like this?

#10
2005-09-14 InvertedM says :

First off, thank you immensely for helping me solve this problem that has had me stumped for about a week now.

Now to my problem(s). First off, when i first load the page (angelsmythe.com/Trial/index.htm) all five of my DIVs display from left to right. as i click on any one of them, they ehave properly from there on out until i reload the page, but i would like to know how to make the page start off correctly.

Next, you will notice that from the start there is a scroll bar on the right, but it disappears if you click either calendar or contact us, and stays gone while clicking anything other than bio, but when it reappears you must click one of the last two nav links to get it to disappear again.

Finally, for some reason when i click on the bio section, even if the scroll bar is already there, everything shifts left a minute amount of space, but shifts back and stays put when you click any of the other links.

Thank you again for your assistance and i look forward to hearing from you soon.

#11
2005-09-15 BonRouge says :

InvertedM,
Funnily enough, I had the same problem recently with another script and someone who knows more about javascript than I do set me right... You have an onload event in the script you copied from here and you have another in your body tag. The second cancels out the first.
So, if you take this :onLoad="runShow()" out of your body tag and change this : window.onload=function () {switch1('one')} to this : window.onload=function () {switch1('one');runShow();}you should be OK.

I'm afraid I can't see the other problems you mention... I don't know what to say... What am I missing?

By the way, I noticed that you've used the same id ('navlink') 5 times. You should use a class.

#12
2005-12-31 Circuit7 says :

So how would I alter the Javascript if I wanted story one displayed all the time and only display story two if the user clicked on the link? I've hunted for an example of this and can't find one.

#13
2006-01-01 BonRouge says :

Circuit7,
I'm not sure if I've understood correctly, but I think what you're asking for is very similar to when people use javascript instead of CSS for image-swaps in menus - they use 'onmouseover' and 'onmouseout'. To do what I think you want, we can use 'onmousedown' and 'onmouseup' - like this.
I hope this helps.

#14
2006-02-05 Guntracy says :

This is the best page i have come across regarding
an easy way to switch content inside a page.
But what if i have a series of tutorials,that i can
choose form a sidebar.
And for each sidebar buttonmthere is a number of pages
that i can call from this "switching content" javascruipt.
I find it hard to to.Is there an easy way?
I can call the div from the barlinkmi have tried this .
Geir gundersen
Guntracy@start.no

#15
2006-02-06 BonRouge says :

Guntracy,
You should be able to do this in the same way - just put each tutorial in its own div and do the same as the above - just move the links to the sidebar.
If these tutorials are quite big though, I wouldn't do this - I'd just use php and do it something like this site - have a sidebar which has fixed positioning for Firefox/Netscape users and let it degrade nicely to absolute positioning for IE users. (I actually had a problem with Opera, so I hacked it to work like IE). To do this with php, you just make a simple template and call the content in. I did this by following an article on A List Apart.
If you want to show me your page and tell me exactly what you're doing, I'll see if I can help out.

#16
2006-02-13 Sayian says :

Great stuff ben ... great stuff .. keep it comin.

#17
2006-02-13 BonRouge says :

'ben'? confused

#18
2006-02-15 Belle says :

Hi BonRouge, I love your pages! :O) I am looking for a coding to click on a picture section and retrieving the text on the bottom. Do you have a tip for me?
Thank you, Belle

#19
2006-02-16 BonRouge says :

Belle,
Sorry, can you explain more clearly? I don't understand what you mean.

#20
2006-03-16 Chean says :

Wow, at last! I found the solution for my problem. I was searching for this for more than a week now and did not find any topics related to switching of contents. I was so happy to see that I was not stupid when I thought of switching the contents on the same page. This bothered me a lot so I want to thank you for this nice tutorial. I really like this site, you explained a hard topic with layman's terms which were easily understood by anyone. Great job, Bon Rouge! very happy

#21
2006-04-11 Eytan says :

Dude, I gotta hand it to you. This was a well explained, simple and effective solution. Finished writing code for the same exact thing and googled to see if something was available to compare with...but yours look nicersmile Kudos.
Smooth Sailing

#22
2006-04-11 BonRouge says :

Eytan,
What can I say? Thanks smile

#23
2006-05-06 Shira says :

I've tried to implement this code a bit differenly: I wanted to switch between 2 divs that contain blocks of text, but I needed the button to switch from a 'next' arrow when the first block of text is displayed to a 'back' arrow for the second one.
So I've put each arrow in a div, and inserted each of these divs into its respective target div (i.e. the 'next' arrow into div 'one' and the 'back' arrow into div 'two'). I then put each button image inside the javascript href tag.
It didn't work.
So am I doing it wrong, or is it just not possible?

#24
2006-05-07 BonRouge says :

Shira,
That sounds like it would work OK. Would you like to show me your page? You could post a link to it or contact me through my contact form. (The form's a bit dodgy though, so just write a short note).

Actually, another way to do it would be to leave the arrow out of the divs and add a line to the script that changes the src of the image: something like this :document.images["next"].src = 'back.jpg';

#25
2006-05-07 Shira says :

this is the page (it's in Hebrew, so what you're looking for is the block of text on the right hand side with an arrow under it)
I apologise for my ignorance, but where would I put this line for changing the image source? it should go inside a condition, shouldn't it? and shouldn't there be another line for changing the image back?
Thanks for your help,
Shira

#26
2006-05-07 BonRouge says :

Shira,
I must admit, I couldn't find the problem for ages, and then I kicked myself when I did find it...
In the 'onclick' part, you need to put the div that you want to show. You've put the same thing in both of the links. To fix the problem, add a '2' to your first link. i.e. onclick="switch1('trainerstext2')"

#27
2006-05-07 Shira says :

Obviously...
Silly me.
Thanks a lot for your help. Much appreciated.

Shira

#28
2006-05-11 Wizborg says :

Hi BonRouge...

Thanks for this, but is there any way of having a transition effect happen when you click??

Chrs

#29
2006-05-11 BonRouge says :

I'm afraid I don't know about transitions. I think that's IE proprietary stuff, which I don't really try to learn much about.

#30
2006-05-11 Wizborg says :

I've found a site that uses them, and I'm trying to reverse engineer it, but not knowing much about Javascript, it's taking time... The site is Here, it's the Portfolio section on the main page, and the transitions work in FF...

#31
2006-05-11 BonRouge says :

Wizborg,
Maybe I'm a bit slow, but I can't see any transition effects on that site... frown

#32
2006-05-11 Wizborg says :

No probs..lol..
Under portfolio latest, if you click "Body Perfection UK" or "Ivy House Designs", there are div toggles with a transition effect... If I can reverse engineer it before you, I'll let you know... It may be a learning experience for us both.. very happy

#33
2006-05-11 Wizborg says :

I think it has something to do with this part in "/common.js"

if(document.getElementById("homepage"))
{
var portfolioItems = document.getElementById("homepage").getElementsByTagName("div");
for (var i=0; i<portfolioItems.length; i++)
{
if(portfolioItems[i ].className == "portfolioItem")
{
portfolioItems[i ].onmouseover=function() { this.className += " pover"; }
portfolioItems[i ].onmouseout=function() { this.className = "portfolioItem"; }
}
}
}


As I said, I'm not too good on Javascript, and struggling to understand each section, but saw the for statement and the ref's to portfolio... If you can help me to understand this it'd be great...


#34
2006-05-11 Wizborg says :

Ah-hah, Looks like I've traced the transition JS stuff.. This page Here

If you could have a look and let me know what you think...

#35
2006-05-12 BonRouge says :

Wizborg,
I've had a good look and I changed things around a little. I hope this is useful to you because it took me a while smile
Here's the page.
If you go there and click 'Create Page' on the left menu, you'll have the code on a page without my menus and stuff.
I've added a few comments to the script so it should be easy for you to take it and apply it to your page.
If you want more than one of these on your page, you'll need to change the code a bit... (come back and maybe I'll help out... wink ).
By the way, as I said earlier, this is just for IE. The image-switching works fine in Firefox, but not the transition. frown It's a shame though, because I quite like the effect. Maybe the people at Mozilla should consider copying IE - and it's not often you'll catch me saying that.

#36
2006-05-12 Wizborg says :

That's great Bon, Thanks for your help, it is a nice effect, I'll probably use it, but I've just found the one that I meant Here.

They've not commented it very well, so I'll have to experiment and figure out what does what, hope it helps you as well...

Loadsa thanks again.
Wizborg.

#37
2006-06-12 Appu says :

Fantastic work!!



thanks.
appu

#38
2006-06-15 Roel says :

Is it possible that if you come from say the home page to the page that contains the three texts, that text number 2 shows directly and that if you come from another page then home that you first will see text number 1 ?

If it's possible can you tell me how ?

#39
2006-06-15 BonRouge says :

Roel,
Yes, you could do that a few ways. What I'd do is pass a variable through the url to some php on the page with the three bits of text. The php would check to see if the variable was present, and if it was, it would make the onload event show the second bit of text instead of the first.

Here's some php I just added to this page :<?php if ($page=='switchcontent' && isset($_GET['sc2'])) {
echo '<script type="text/javascript">
window.onload=function() {switch1("two");}
</script>';
}
?>


Now, if you follow this link you should see that working.

#40
2006-07-11 BonRouge says :

Adam H,
I'm sorry I've deleted your post, but it was doing something really weird to my page - I need to look into the problem. I haven't just deleted your post though, I have saved it...here.

Anyway, I looked at your page and I think one of these might help you:
http://bonrouge.com/test/sftoggle.htm
http://bonrouge.com/test/sftoggle2.htm

Let me know if that's what you're after or if you have any questions.

#41
2006-07-12 Adam H. says :

Thanks BonRouge. I ended up solving it another way.

#42
2006-08-06 pixeljockey says :

this is so close to what i need, but wanting to use NEXT and PREVIOUS instead of explicit links (story one, story two, etc)

#43
2006-08-08 Genevieve says :

Thank you BonRouge for providing such a fantastic script. I was in the verge of giving up to find this!
I have one little question about when I try to verify the script in W3C. It tells me that the ; after the command option.length is not allowed as a character and ends up making option.length undefined. Do you know what I might be able to do to fix this?

#44
2006-08-18 Joel A. Burdick says :

You are doing some fantastic work! I come here often enough, searching for something to improve the look & feel of my work... and I learn something new every time!

Thanks!!
-Joel

#45
2006-09-14 Chad D. says :

Hi. I've been using this code for a while on my page but now I need it to have quite a few more divs that it can show/hide. I need it to handle up to 50 divs - so I tried to write a for loop to make a new array with 50 possible divs like this
function itemSelect(divy) {
var option;
for(var k=0; k<50; k++) {
noption[k] = 'div'+k;
}
for(var j=0; j<option.length; j++) {
if (document.getElementById(option[j])) {
nobj=document.getElementById(option[j]);
obj.style.display=(option[j]==divy)? "block" : "none";
}
}
}

window.onload=function() {itemSelect('div0');}


However, when I load my page it says that there's an error on line 5 at char 1. The error is "Object Expected". I don't what's wrong - can you help?

#46
2006-09-14 BonRouge says :

Chad D,
See if this helps:new 'switchcontent' page

#47
2006-09-14 Chad D. says :

Hi, thanks for the response but I don't think that method will work for me because I already use classes on my switched divs. Also, these classes are not all the same, thus the reg expression check wouldn't work either. Sorry, but is there just a way to take this original method and make it work with div id's like div0, div1, div2 ... div49 instead of using divs like divOne, divTwo, divThree ... divFortynine ... I want to do it this way so I can use my PHP to automatically spit out div0, div1, div2 ... div49 and unfortunately you can't easily spit out divOne, divTwo, divThree ... divFortynine with PHP???

#48
2006-09-14 BonRouge says :

First, you should initialise the array, then take the 'var' out of the 'for' loops. This should work for you;function itemSelect(divy) {
var option=new Array();
for(k=0; k<50; k++) {
option[k] = 'div'+k;
document.write(option[k])
}
for(j=0; j<option.length; j++) {
if (document.getElementById(option[j])) {
obj=document.getElementById(option[j]);
obj.style.display=(option[j]==divy)? "block" : "none";
}
}
}

window.onload=function() {itemSelect('div0');}

#49
2006-09-14 Chad D. says :

BonRouge! Thanks so much that did the trick. Have a great day!

#50
2006-10-09 Mikey says :

Hey im having a problem similar to #10... where when the page first loads it displays all 5 of my <div>'s.. it works properly after clicking on one of the links.. but if i refresh the page it goes back to displaying all them. I tryed adding ;runShow(); to the script but it didnt work for me.. maybe im doing somthing wrong?

Anyways thanks for this script.. i've been looking for one like this for a while. smile

#51
2006-10-09 Mikey says :

Never mind.. i didn't realize i had to take out the preloaded images i had in the <body> tag smile

#52
2007-02-23 Ivonne says :

Hey, this is a great script. I was wondering though do you know if there is anyway to make the active story's link bold or decorated in some way to differentiate it from the other links?

#53
2007-02-24 BonRouge says :

Ivonne,
Here's one way.

#54
2007-07-12 Squeak says :

This is a great tutorial, but I am looking for something a little more complex. Is there a way - in CSS - to make a mouseover video gallery? For example, I have 10 videos I would like to display on my site, I would like to have them listed in a div on the right side of the screen. My ultimate result would be to have each video appear or load in a center div on mouseover. Or maybe have a screenshot from the video appear in the center div on mouseover and the video load into the center div onclick. Any ideas how to do this?

#55
2007-07-12 Squeak says :

Nevermind... took me a little effort to get it just right.. but I figured it out! Thanks much!

#56
2007-09-20 quibbles says :

Brilliant work ,worked a treat first time i just have one question when the page loads first time all the content of one two and three are visable is it possible two make just one apear first then the user can click to see two and three?

#57
2007-09-20 BonRouge says :

quibbles,
Yeah, I know what you mean. My solution to this is explained around the bottom of this page here: http://bonrouge.com/~clickdrop
I hope that helps.

#58
2007-10-16 Pang says :

i have used ur script, its pretty good, however when i click on the link, then the content of div was beeing large, any solution?

#59
2007-10-16 BonRouge says :

Pang,
See the link in the comment just above yours.

#60
2007-10-16 pang says :

Thanks for your kindly reply
however, it doesnt solve my problem
my problem is
when i click on the link
the other heading size and font size is being large
i want to have a fixed size
so let see you can help me or not
PS. css doent help any thing except i chant the font size into large, i try before

#61
2007-11-18 n8 says :

Thank you for the div switching javascript. It's has been very useful.

In your example you used a series of words (text) to switch out divs. I used a series of jpg files on my site and it work just as well. I then used it on a larger single image and the used chords to section off areas of the image. It's in a menu at the top of a page. When I view it if firefox, the chorded of sections switch out a div under the image and it works very well as a menu.

The problem is that this doesn't work in Safari or IE. Any thought? Is there something I am missing? Let me know if you need an example to clarify.

#62
2008-07-02 Woo says :

Woo+yay=wooyay

#63
2008-11-08 Richard Metcalfe says :

I also have the problem with the text being large.

Regards,
Rich
Web Development & Hosting

#64
2008-11-26 Sunny says :

hi i find this tutorial very useful. thank u very much

#65
2008-11-26 Sunny says :

hi thanks for the posting.

but i have a problem in it.
i have loaded swf video file in five div, when one video is playing and we click on second div the first video is not stoping it remain playing in background.
the sound of first video is coming with the sound of second video and we go to first div it will show the video is playing not stopped

need your help any script to stop first video when loading second div or video.

#66
2010-11-30 Liam says :

Unreal - THANKS

#67
2011-09-28 Fred says :

Thank you!
Works great

#68
2012-01-10 Marty says :

Great Info! Thanks.
I'd like to be able to control visibility with a date. For example I need a text that says "New Store Hours" to 'disappear' after two weeks or a month. Can anyone help me here?

#69
2012-01-15 BonRouge says :

Marty,
You can do that with PHP if you're using it - something like this:

<?php
$text = "<p>New opening hours: etc...</p>";
$enddate = mktime(0,0,0,2,1,2012); // February 1st 2012
if (time() < $enddate) {
echo $text;
}
?>


If you want to use javascript, you could do it something like this. Give your element with the text that you want to make disappear an id, let's say "newhours". Then in the javascript:


<script type="text/javascript">
function hideHours() {
var d = new Date();
var rightNow = d.getTime(); // This should give unix time in milliseconds.
if (rightNow < 1328054400000) { // milliseconds of unix time until February 1st 2012
document.getElementById("newhours").style.display="none"; // Hide the element.
}
}
window.onload=hideHours;
</script>


You can get the unix time in seconds from here: http://www.onlineconversion.com/unix_time.htm.
The javascript one is a bit hacky, but it should do the job.

I hope that helps.

Comment form

Please type the word 'brown' here:

BB code available :

  • [b]...[/b] : bold
  • [it]...[/it] : italic
  • [q]...[/q] : quote
  • [c]...[/c] : code
  • [url=...]...[/url] : url