Reputation: 1789
<script type="text/javascript">
function ToggleList(IDS) {
var CState = document.getElementById(IDS);
if (CState.style.display != "block") { CState.style.display = "block"; }
else { CState.style.display = "none"; }
}
</script>
<style type="text/css">
.divInfo
{
display: none;
}
</style>
<p>Text</p>
<a onclick="ToggleList('LT3')">Show More</a>
</p>
<div id="LT3" class="divInfo">
<p>Additional Test</p>
</div>
This works great, but I'd love to have the label "Show More" change to "Hide" when the toggle is expanded. Any ideas on how to do that? CState.innertext = "Hide" ?
Upvotes: 0
Views: 1708
Reputation: 111
The CState object in your function is a reference to the DIV. What you should do is give the anchor tag an ID, and then change the text inside of that.
function ToggleList(anchorID, IDS) {
var CState = document.getElementById(IDS);
var anchor = document.getElementByID(anchorID);
if (CState.style.display != "block") {
CState.style.display = "block";
anchor.innerHTML = "Hide";
} else {
CState.style.display = "none";
anchor.innerHTML = "Show more";
}
}
Your anchor tag would then look like this:
<a id="listToggle" onclick="ToggleList('listToggle', 'LT3')">Show More</a>
Upvotes: 3
Reputation: 48761
To gain browser compatiblity, create a variable like this:
var text = 'textContent' in document ? 'textContent' : 'innerText';
Then use it like this:
CState[text] = "New Text Content";
But it seems like you want to change the label of the <a>
, not the <div>
. So you'd do this to your HTML:
<a onclick="ToggleList(this, 'LT3')">Show More</a>
And then this to your JS:
var text = 'textContent' in document ? 'textContent' : 'innerText';
function ToggleList(anchor, IDS) {
var CState = document.getElementById(IDS);
if (CState.style.display != "block") {
CState.style.display = "block";
anchor[text] = "Hide";
} else {
CState.style.display = "none";
anchor[text] = "Show More";
}
}
DEMO: http://jsfiddle.net/RRUEY/
Upvotes: 3
Reputation: 870
I believe you will want to add an id to the tag, for example:
<a id='txtShowMore' onclick="ToggleList('LT3')">Show More</a>
Then have this script:
var showMoreElement = document.getElementByID('txtShowMore');
showMoreElement.innerHTML = "Hide";
And then of course, the same thing for setting it back to "Show More" when you hide it.
Upvotes: 1
Reputation: 101604
Pass a reference of the <a>
to the function, then refactor the function a bit to re-tag it based on visibility:
function ToggleList(anchor,IDS) {
var CState = document.getElementById(IDS);
var isVisible = (CState.style.display == "block");
anchor.innerHTML = isVisible ? 'Show more' : 'Hide';
CState.style.display = isVisible ? 'none' : 'block';
}
The altered HTML:
<a onclick="ToggleList(this,'LT3')">Show More</a>
Upvotes: 1