Wednesday, September 26, 2012

Show/Hide Text in Blogger with Javascript

I wanted to be able to hide some text by default when the page loads and then show it when a user clicks on the link to show it. Initially, I couldn't get this to work in Blogger (or so I thought). Turns out that it just doesn't work on the Preview page that Blogger provides from the editing window.

Anyways... If you are looking for code on this here it is (I add it at the end of a post):
<script language="javascript">
function toggle(togID, dispID) {
var ele = document.getElementById(togID);
var text = document.getElementById(dispID);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
Originally this code came from here: http://bloggerstop.net/2009/01/how-to-showhide-text-using-javascript.html

However, the author suggested making a toggle1(), toggle2(), toggle3(), etc for each Show/Hide block you wanted. And the author warns that with enough of these blocks you will slow down the blog.

So the code I provide above is a slightly modified version of the code at the link I provided. Specifically, it requires that you now pass in the id values of the div you want to Show/Hide. To use the javascript above you need to do something like this:
<div dir="ltr" style="text-align: left;" trbidi="on"><a href="javascript:toggle('toggleText', 'displayText');" id="displayText">Show</a>
<br />
<div id="toggleText" style="display: none;">
This is Hidden Text #2</div>
</div>
Live Examples:

1 comment:

  1. I know that this post is old but I have a question.
    The second code you give, how it's used in the same post, twice, to hide differente things?

    Probably I'll never get a respond but I need to try.

    ReplyDelete