/    Sign up×
Community /Pin to ProfileBookmark

Toggle() to show/hide text

Hello,

I’m new to JS and am looking for guidance. I am trying to write a script that that will allow me to post a list of topics (list of <div>’s) and then when the topic (<div>is clicked text is posted under that topic. When the topic is clicked again the text is hidden.

I found that a toggle() function works well for this, and I’ve been able to make it work with only one <div> using getElementById(). My question, how can I configure the script so that I can create a list of topics.

Example:

Item1 Item1
Item2 —clicking on Item2 Item2
Item3 Item 2 information here
Item3

Here is the code I’m using:

function toggle() {
var ele = document.getElementById(“toggleText”);
var text = document.getElementById(“displayText”);

if(ele.style.display == “block”) {
ele.style.display = “none”;
//text.innerHTML = “show”;
}
else {
ele.style.display = “block”;
//text.innerHTML = “hide”;
}

}

<a id=”dispayText” href=”javascript:toggle();”>Item 1</a>
<div id=”toggleText” style=”display: none”>Info on item 1
<P>
<a id=”dispayText” href=”javascript:toggle();”>Item 2</a>
<div id=”toggleText” style=”display: none”>Info on item 2</div>
<P>
<a id=”displayText” href=”javascript:toggle();”>Item 3</a>
<div id=”toggleText” style=”display: none”>Info on item 3</div>

I know that I need to change the id’s for each item.

Any guidance would be greatly appreciated.

Cheers,
John

to post a comment
JavaScript

11 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERSep 11.2014 — ID values MUST be unique. Even for testing purposes.

Consider this modification.
<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;

&lt;title&gt; HTML5 page &lt;/title&gt;

&lt;style type="text/css"&gt;
.show { display:block; }
.hide { display:none; }
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;a href="#" onclick="return toggle('toggleText0')"&gt;Item 1&lt;/a&gt;
&lt;div id="toggleText0" class="hide"&gt;Info on item 1&lt;/div&gt;
&lt;p&gt;
&lt;a href="#" onclick="return toggle('toggleText1')"&gt;Item 2&lt;/a&gt;
&lt;div id="toggleText1" class="hide"&gt;Info on item 2&lt;/div&gt;
&lt;p&gt;
&lt;a href="#" onclick="return toggle('toggleText2')"&gt;Item 3&lt;/a&gt;
&lt;div id="toggleText2" class="hide"&gt;Info on item 3&lt;/div&gt;

&lt;script type="text/javascript"&gt;
function toggle(info) {
var elem = document.getElementById(info);
if (elem.className == "hide") { elem.className = 'show'; } else { elem.className = 'hide'; }
return false;
}

&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
Copy linkTweet thisAlerts:
@TcobbSep 11.2014 — (1) CLOSE YOUR TAGS

Rather than doing what you're doing I would structure it something like this:

[CODE]<a class="displayText">Item 1</a><br>
<div style="display: none">Info on item 1</div>
<a class="displayText">Item 2</a><br>
<div id="toggleText" style="display: none">Info on item 2</div>[/CODE]


I would however, set the "display" on the info to none by using a class.

Now for the javascript:

[CODE]function toggle(){
var v;
v = this.nextSibling;
while(v.nodeType !== 1){
v = v.nextSibling;
}
if(v.style.display != 'none'){
v.style.display = 'none';
}
else{
v.style.display = "";
}
}[/CODE]


and to actually make it work, put the following code in your "window.onload" function,

[CODE] var len, a = document.getElementsByClassName('displayText');
len = a.length;
while(len--){
a[len].onclick = toggle;
}[/CODE]


or set it up as a self-executing function right before the </body> tag.

There are many ways to accomplish what you want to do, including the HTML5 DETAILS SUMMARY tags (but I don't know what, if any, browsers currently support those tags).
Copy linkTweet thisAlerts:
@crocketerSep 13.2014 — Hi - me too!

I'm no expert and our genius is away so I'm hoping for some help with what we've got rather than a new approach. Unfortunately I don't really understand enough to start afresh.

We have a WordPress (hosted) site and a Page (not Post) needing four sections that simple reveal (show/hide) additional copy text. In each section of the Page there's a first para then 'More...' - nothing fancy.

It works fine on one instance if we start the Page html with JavaScript:

<script type="text/javascript" language="javascript">// <![CDATA[

function toggle() {

var ele = document.getElementById("toggleText");

var text = document.getElementById("displayText");

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

ele.style.display = "none";

text.innerHTML = "Show";

}

else {

ele.style.display = "block";

text.innerHTML = "Hide";

}

}

// ]]></script>

Then wrap the content:

<div id="toggleText" style="display: none;"> more text between these tags </div>

Then make the click:

<a id="displayText" href="javascript:toggle();">Show more...</a>

BUT taking the advice we have on multiple instances in one Page doesn't work. The advice is to repeat the JS and use IDs for toggleText and displayText.

But doing that, the last copy of the JS is always the one that triggers, whatever is clicked.

This is what we have (and the person who advised isn't about...) - it's just four copies of the JS with toggleText and displayText numbered:

<script type="text/javascript" language="javascript">// <![CDATA[

function toggle() { var ele = document.getElementById("toggleText1"); var text = document.getElementById("displayText1"); if(ele.style.display == "block") { ele.style.display = "none"; text.innerHTML = "More ..."; } else { ele.style.display = "block"; text.innerHTML = "... less"; } }

// ]]></script>

<script type="text/javascript" language="javascript">// <![CDATA[

function toggle() { var ele = document.getElementById("toggleText2"); var text = document.getElementById("displayText2"); if(ele.style.display == "block") { ele.style.display = "none"; text.innerHTML = "More ..."; } else { ele.style.display = "block"; text.innerHTML = "... less"; } }

// ]]></script>

<script type="text/javascript" language="javascript">// <![CDATA[

function toggle() { var ele = document.getElementById("toggleText3"); var text = document.getElementById("displayText3"); if(ele.style.display == "block") { ele.style.display = "none"; text.innerHTML = "More ..."; } else { ele.style.display = "block"; text.innerHTML = "... less"; } }

// ]]></script>

<script type="text/javascript" language="javascript">// <![CDATA[

function toggle() { var ele = document.getElementById("toggleText4"); var text = document.getElementById("displayText4"); if(ele.style.display == "block") { ele.style.display = "none"; text.innerHTML = "More ..."; } else { ele.style.display = "block"; text.innerHTML = "... less"; } }

// ]]></script>

Then the wrap and click are each numbered too, eg:

<a id="displayText1" href="javascript:toggle();"><span style="color: #339966;">Show more ...</span></a>

<div id="toggleText1" style="display: none;">

More text 1

</div>



QUESTION: can this approach work? It looks as though there needs to be some sort of ID for the toggle function itself to tie it to one ('numbered') instance.

Thanks for reading this far... C
Copy linkTweet thisAlerts:
@cootheadSep 13.2014 — Hi there embdriver,

[indent]

and a warm welcome to these forums. ?

You might prefer a [b]CSS[/b] toggle method instead. ?

Here is an example...
[color=navy]
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;

&lt;meta charset="utf-8"&gt;

&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;

&lt;title&gt;CSS toggling&lt;/title&gt;

&lt;style media="screen"&gt;
body {
background-color:#f0f0f0;
font-size:100%;
}
#container {
width:40%;
padding:0.4%;
border:0.1em solid #999;
border-radius:1.2em 1.2em 0 0;
margin:auto;
color:#333;
background-color:#fff;
box-shadow:0.3em 0.3em 0.3em #666;
}
input {
display:none;
}
input + label:before{
content:'&amp;#9660; show';
}
input:checked + label:before {
content:'&amp;#9650; hide';
}
input ~ div { <br/>
height:0;
border-right:0.1em solid #999;
border-left:0.1em solid #999;
border-top:0;
overflow:hidden;
font-size:90%;
box-shadow:inset 0 0 0.5em #999;
background-color:#fcfcfc;
}
input:checked ~ div {
padding:0 5%;
overflow:auto;
-webkit-animation:2s open forwards; <br/>
animation:2s open forwards;
}
label {
display:block;
line-height:2;
padding:0 3%;
color:#fff;
background-color:#333;
background-image:linear-gradient(to bottom,#ddd,#222);
text-shadow:0 0 1px #000, 0 0 2px #000, 0 0 3px #000;
cursor:pointer;
}
input:checked ~ label {
background-image:linear-gradient(to bottom,#ddf,#226);
}
#container div:first-of-type label{
border-radius:1em 1em 0 0;
}
#container div:last-of-type div{
border-bottom:0.1em solid #999;
}
@-webkit-keyframes open {
from {
height:0;
}
to {
height:190px;
}
}
@keyframes open {
from {
height:0;
}
to {
height:190px;
}
}
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;

&lt;div&gt;
&lt;input id="cb" type="checkbox"&gt;
&lt;label for="cb"&gt;&lt;/label&gt;

&lt;div&gt;
&lt;p&gt;
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec
ultricies sollicitudin nisi, ut molestie felis adipiscing sit
amet. Sed auctor vehicula commodo. Nam a nibh neque, vitae
faucibus felis. Vivamus at metus eget eros consequat fringilla.
Quisque magna magna, laoreet eu tempus sit amet, fringilla at
tellus. Praesent felis tortor, scelerisque vitae fringilla
non, porttitor et lacus. Ut ut sapien nec quam tincidunt
consectetur in nec lacus.
&lt;/p&gt;
&lt;/div&gt;

&lt;/div&gt;&lt;div&gt;

&lt;input id="cb1" type="checkbox"&gt;
&lt;label for="cb1"&gt;&lt;/label&gt;

&lt;div&gt;
&lt;p&gt;
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec
ultricies sollicitudin nisi, ut molestie felis adipiscing sit
amet. Sed auctor vehicula commodo. Nam a nibh neque, vitae
faucibus felis. Vivamus at metus eget eros consequat fringilla.
Quisque magna magna, laoreet eu tempus sit amet, fringilla at
tellus. Praesent felis tortor, scelerisque vitae fringilla
non, porttitor et lacus. Ut ut sapien nec quam tincidunt
consectetur in nec lacus.
&lt;/p&gt;&lt;p&gt;
Phasellus porta, dui a elementum egestas, odio sapien rhoncus
lorem, vitae bibendum erat sem eget sapien. Maecenas ut metus
ac quam pellentesque lacinia quis sit amet augue. Fusce eu
euismod urna. Nunc volutpat scelerisque tempus. Donec eget arcu
et mauris scelerisque tristique. Donec fringilla mauris dolor,
sit amet vulputate lacus. Nulla feugiat mattis nulla non
tincidunt. Nam sit amet dolor eros, a viverra lacus. Nunc quis
nisi eget neque tempus facilisis eu quis sapien.
&lt;/p&gt;
&lt;/div&gt;

&lt;/div&gt;&lt;div&gt;

&lt;input id="cb2" type="checkbox"&gt;
&lt;label for="cb2"&gt;&lt;/label&gt;

&lt;div&gt;
&lt;p&gt;
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec
ultricies sollicitudin nisi, ut molestie felis adipiscing sit
amet. Sed auctor vehicula commodo. Nam a nibh neque, vitae
faucibus felis. Vivamus at metus eget eros consequat fringilla.
Quisque magna magna, laoreet eu tempus sit amet, fringilla at
tellus. Praesent felis tortor, scelerisque vitae fringilla
non, porttitor et lacus. Ut ut sapien nec quam tincidunt
consectetur in nec lacus.
&lt;/p&gt;
&lt;/div&gt;

&lt;/div&gt;

&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;[/color]

[/indent]

[i]coothead[/i]
Copy linkTweet thisAlerts:
@crocketerSep 13.2014 — That's very kind, thank you. Please let me take a look and respond! C
Copy linkTweet thisAlerts:
@crocketerSep 13.2014 — Thanks again coothead but that takes us into new waters and I think we need to first see whether JS can do it.

We're in hosted WP with very clean plain Pages and no panels etc.

The JS solution works very smoothly indeed except when there's more than one instance!

Many thanks, C
Copy linkTweet thisAlerts:
@cootheadSep 13.2014 — Hi there crocketer,

[indent]

if CSS does not agree with your palate, then here is a javascript example for you to try...
[color=navy]
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;

&lt;meta charset="utf-8"&gt;

&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;

&lt;title&gt;javascript toggle&lt;/title&gt;

&lt;style media="screen"&gt;
body {
background-color:#f0f0f0;
font-size:100%;
}
#container {
width:50%;
padding:0.4%;
border:0.1em solid #999;
border-radius:1.2em 1.2em 0 0;
margin:auto;
color:#333;
background-color:#fff;
box-shadow:0.3em 0.3em 0.3em #666;
}
#container span {
display:block;
line-height:2.0;
background-image:linear-gradient(to bottom,#ccc,#333);
color:#fff;
text-indent:2%;
text-shadow:0 0 1px #000,0 0 3px #000,0 0 3px #000;
}
#container span:first-of-type {
border-radius:1em 1em 0 0;
}
#container span:hover {
background-image:linear-gradient(to bottom,#ddf,#226);
}
#container div {
padding:2% 5%;
border:1px solid #000;
box-shadow:inset 0 0 0.5em #999;
background-color:#fcfcfc;
}
.hide {
display:none;
}
&lt;/style&gt;

&lt;script&gt;
(function() {
'use strict';
var cn,sp,dv,c,el,n;
function init(){
cn=document.getElementById('container');
sp=cn.getElementsByTagName('span');
dv=cn.getElementsByTagName('div');
for(c=0;c&lt;sp.length;c++) {
sp[c].number=c;
sp[c].addEventListener('onclick',makeClickHandler(c));
}
}

function makeClickHandler(c) {
sp[c].onclick=function() {
el=this;
n=this.number
toggleStuff(el,n);
};
}

function toggleStuff(el,n) {
if(el.firstChild.nodeValue==='&amp;#9650; hide content') {
el.firstChild.nodeValue='&amp;#9660; show content';
dv[n].className='hide';
}
else {
for(c=0;c&lt;sp.length;c++) {
sp[c].firstChild.nodeValue='&amp;#9660; show content';
dv[c].className='hide';
}
el.firstChild.nodeValue='&amp;#9650; hide content';
dv[n].className='';
}
}
window.addEventListener('load',init,false);
})();
&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;
&lt;div id="container"&gt;

&lt;span&gt;&amp;#9660; show content&lt;/span&gt;
&lt;div class="hide"&gt;content&lt;/div&gt;

&lt;span&gt;&amp;#9660; show content&lt;/span&gt;
&lt;div class="hide"&gt;content&lt;/div&gt;

&lt;span&gt;&amp;#9660; show content&lt;/span&gt;
&lt;div class="hide"&gt;content&lt;/div&gt;

&lt;span&gt;&amp;#9660; show content&lt;/span&gt;
&lt;div class="hide"&gt;content&lt;/div&gt;

&lt;span&gt;&amp;#9660; show content&lt;/span&gt;
&lt;div class="hide"&gt;content&lt;/div&gt;

&lt;span&gt;&amp;#9660; show content&lt;/span&gt;
&lt;div class="hide"&gt;content&lt;/div&gt;

&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;[/color]

[/indent]

[i]coothead[/i]
Copy linkTweet thisAlerts:
@Kevin2Sep 13.2014 — Try this:

[edit: Oops, didn't see Coothead's JS response...]

[code=html]<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Toggle Text</title>
<style>
a.show {
color: #339966;
}
</style>
<script>
function toggle(ele,text) {
if(text.style.display == "block") {
text.style.display = "none";
ele.innerHTML = "Show";
}
else {
text.style.display = "block";
ele.innerHTML = "Hide";
}
}
</script>
</head>
<body>
<a class="show" id="displayText1" href="javascript:toggle(displayText1,toggleText1);">Show more ...</a>
<div id="toggleText1" style="display: none;">
More text 1
</div>
<br>
<a class="show" id="displayText2" href="javascript:toggle(displayText2,toggleText2);">Show more ...</a>
<div id="toggleText2" style="display: none;">
More text 2
</div>
<br>
<a class="show" id="displayText3" href="javascript:toggle(displayText3,toggleText3);">Show more ...</a>
<div id="toggleText3" style="display: none;">
More text 3
</div>
<br>
<a class="show" id="displayText4" href="javascript:toggle(displayText4,toggleText4);">Show more ...</a>
<div id="toggleText4" style="display: none;">
More text 4
</div>
</body>
</html>[/code]
Copy linkTweet thisAlerts:
@crocketerSep 13.2014 — Hi all just received this on anpther forum and it works a treat:

I don't see any need to ever create multiple functions that do the same thing. In general you should pass parameters in the function call. e.g.

<a id="displayText1" href="javascript:toggle(1);">...</a>

<a id="displayText2" href="javascript:toggle(2);">...</a>

<a id="displayText3" href="javascript:toggle(3);">...</a>

<a id="displayText4" href="javascript:toggle(4);">...</a>

and in the javascript:

function toggle(num) {

var ele = document.getElementById("toggleText" + num);

var text = document.getElementById("displayText" + num);

....

}

Works like a charm. Hope this helps... bye for now.
Copy linkTweet thisAlerts:
@cootheadSep 13.2014 — [indent]

the example that I gave in post #8, did not take into account those

users who, for whatever reason, might have disabled javascript. :eek:

This is the appropriate code for that eventuality...
[color=navy]
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;

&lt;meta charset="utf-8"&gt;

&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;

&lt;title&gt;javascript toggle&lt;/title&gt;

&lt;style media="screen"&gt;
body {
background-color:#f0f0f0;
font-size:100%;
}
#container {
width:50%;
padding:0.4%;
border:0.1em solid #999;
border-radius:1.2em 1.2em 0 0;
margin:auto;
color:#333;
background-color:#fff;
box-shadow:0.3em 0.3em 0.3em #666;
}
#container span {
display:block;
height:2em;
line-height:2.0;
background-image:linear-gradient(to bottom,#ccc,#333);
color:#fff;
text-indent:2%;
text-shadow:0 0 1px #000,0 0 3px #000,0 0 3px #000;
cursor:pointer;
}
#container span:first-of-type {
border-radius:1em 1em 0 0;
}
#container span:hover {
background-image:linear-gradient(to bottom,#ddf,#226);
}
#container div {
padding:2% 5%;
border:1px solid #000;
box-shadow:inset 0 0 0.5em #999;
background-color:#fcfcfc;
}
.hide {
display:none;
}
&lt;/style&gt;

&lt;script&gt;
(function() {
'use strict';
var cn,sp,dv,c,el,n;
function init(){
cn=document.getElementById('container');
sp=cn.getElementsByTagName('span');
dv=cn.getElementsByTagName('div');
for(c=0;c&lt;sp.length;c++) {
dv[c].className='hide';
sp[c].number=c;
sp[c].innerHTML='&amp;#9660; show content';
sp[c].addEventListener('onclick',makeClickHandler(c));
}
}

function makeClickHandler(c) {
sp[c].onclick=function() {
el=this;
n=this.number
toggleStuff(el,n);
};
}

function toggleStuff(el,n) {
if(el.innerHTML==='&amp;#9650; hide content') {
el.innerHTML='&amp;#9660; show content';
dv[n].className='hide';
}
else {
for(c=0;c&lt;sp.length;c++) {
sp[c].innerHTML='&amp;#9660; show content';
dv[c].className='hide';
}
el.innerHTML='&amp;#9650; hide content';
dv[n].className='';
}
}
window.addEventListener('load',init,false);
})();
&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;

&lt;span&gt;&lt;/span&gt;
&lt;div&gt;content&lt;/div&gt;

&lt;span&gt;&lt;/span&gt;
&lt;div&gt;content&lt;/div&gt;

&lt;span&gt;&lt;/span&gt;
&lt;div&gt;content&lt;/div&gt;

&lt;span&gt;&lt;/span&gt;
&lt;div&gt;content&lt;/div&gt;

&lt;span&gt;&lt;/span&gt;
&lt;div&gt;content&lt;/div&gt;

&lt;span&gt;&lt;/span&gt;
&lt;div&gt;content&lt;/div&gt;

&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;[/color]


Having said that, none of the other solutions offered have taken that

consideration into account. ?

[/indent]

[i]coothead[/i]
Copy linkTweet thisAlerts:
@crocketerSep 13.2014 — Good point...
×

Success!

Help @embdriver spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...