Saturday, January 29, 2011

Show/Hide Content with CSS and JavaScript

Code2HTML is a syntax highlighter which reliefs the painful task of transcribing code to html pages.

Sometimes the code occupies too much of the web page, so it is better to be able to hide it.
It seems that there are many ways of hiding parts of a web page, most rely on CSS and javascript to modify the page.

Here I'm using the script from: http://www.cssnewbie.com/showhide-content-css-javascript/. Below is the code for I'm using in this page.

Some notes:
  • the default state (shown/hidden) depends on which tag that has the: style="display: none;"
  • The tags ID are very important. The elements MUST be named as id="code123" for the hidden content, and the other id="code123-show" for the visible link to the hidden content.
  • The tag ID must be UNIQUE for this element within the current page, otherwise it will affect all the other tags.


Try it! Hide the code

<script type="text/javascript">
<!-- code from http://www.cssnewbie.com/showhide-content-css-javascript/ -->
function showHide(shID) {
 if (document.getElementById(shID)) {
  if (document.getElementById(shID+'-show').style.display != 'none') {
   document.getElementById(shID+'-show').style.display = 'none';
   document.getElementById(shID).style.display = 'block';
  }
  else {
   document.getElementById(shID+'-show').style.display = 'inline';
   document.getElementById(shID).style.display = 'none';
  }
 }
}
</script>


<a class="showLink" href="#" id="code123-show" onclick="showHide('code123');return false;">
See the code.
</a>
<div id="code123" 
style="display: none; border-top: 1px solid #666; border-bottom: 1px solid #666;">
<!-- PUT YOUR CONTENT FROM HERE -->
YOUR CONTENT

YOUR CONTENT

YOUR CONTENT
<!-- TO HERE -->
<p>
<a href="#" id="code123-hide" class="hideLink" onclick="showHide('code123');return false;">
Hide this content.
</a>
</p>
</div>

<!-- syntax highlighted by <a href="http://www.palfrader.org/code2html">Code2HTML</a>, v. 0.9.1 -->

No comments:

Post a Comment