New Revised CSS Library Forums Web Tools
FAQs Awards Usage Terms Contact
Categories
Other Sections
Sweet Ads
Compatibility
Bookmark online:

FF1+ IE5+ Opera7+

Switch Content Script

Author: Dynamic Drive

Notes:

  • Jan 25th, 07: to fix a bug with the defaultExpanded() feature not being honoured when persistence is enabled. Only applicable the first time the page is loaded within a browser session. Only .js file changed!
  • April 5th, 07: Added ability to persist content states by x days versus just session only. Only .js file changed!
  • March 27th, 08': Added ability for certain headers to get its contents remotely from an external file via Ajax. Only .js file changed!

Description: One of the most versatile scripts of its kind, we created this one to compact arbitrary content on your page so they're expandable on demand. This allows you to save space within your webpage and even add to the aesthetics of the webpage's design in many cases. What sets this script apart from most other you'll find are the following features:

  • Works unobtrusively in all modern browsers. Those with JavaScript disabled will simply see all the contents expanded by default.
  • Supports multiple "groups" of switch contents on the same page, each with their own independent settings.
  • Decide whether to collapse previous content when expanding the current, so only one content can be open at any time.
  • Specify arbitrary HTML to prefix the headers to indicate open and closed states, such as an open and closed bullet image.
  • New! Ability for certain headers to get its contents remotely from an external file on the server via Ajax, fetched only when header is expanded.
  • Set the color of the headers when its content is open or closed, respectively.
  • Supports persistence of content states using session or non-session cookies, so navigating away from the page and revisiting it won't reset their states.
  • Specify which contents (if any) should be expanded by default. Note that cookie feature if enabled overrides this setting.

Most of the features listed are optional and can be enabled/ disabled as desired. Yes your mind is running wild with ideas now...

Demo 1:

What is JavaScript?

JavaScript is a scripting language originally developed by Netscape to add interactivity and power to web documents. It is purely client side, and runs completely on the client's browser and computer.

Difference betwen Java & JavaScript?

Java is completely different from JavaScript. The former is a compiled language while the later is a scripting language.

What is DHTML?

DHTML is the embodiment of a combination of technologies- JavaScript, CSS, and HTML. Through them a new level of interactivity is possible for the end user experience.
Demo 2:

What is JavaScript?

Difference betwen Java & JavaScript?

What is DHTML?

DHTML is the embodiment of a combination of technologies- JavaScript, CSS, and HTML. Through them a new level of interactivity is possible for the end user experience.


Notes for demo #1:
  • Two images are used as the status indicators.
  • "Collapse Previous" setting is enabled, so only one content allowed open at any time.
  • Expand All/ Collapse All links defined to view or hide all contents.
  • Persistence feature enabled.
  • Custom open/close header colors enabled

Notes for demo #2:
  • The text "[open]" and "[closed]" are specified as the status indicators.
  • First and second contents expanded by default when page loads.
  • First and second contents are remotely fetched via Ajax (file1 and file2).
  • Persistence feature disabled.
  • Custom open/close header colors enabled

Directions: Developer's View

Step 1: Add the following code into the <HEAD> section of your page:

Select All

The code references an external .js file, which you should download below:

Step 2: Then, insert the below sample HTML to the BODY of your page, which shows the two demos above:

Select All

More information

This script works with virtually any content on your page to make them expandable. The process is always the same, which consist of the below 2 steps:

Step 1: Define your contents and content headers to participate in the "switching". For example:

<h3 id="bobcontent1-title" class="handcursor">What is JavaScript?</h3>
<div id="bobcontent1" class="switchgroup1">
JavaScript is a scripting language originally developed by Netscape to add interactivity
and power to web documents. It is purely client side, and runs completely on the client's browser and computer.
</div>


<h3 id="bobcontent2-title" class="handcursor">Difference between Java & JavaScript?</h3>
<div id="bobcontent2" class="switchgroup1">
Java is completely different from JavaScript.
The former is a compiled language while the later is a scripting language.
</div>

Here I have two contents (plus their headers) I wish to contract/ expand dynamically via this script. The only protocol you must follow is to give each content container a unique ID (ie: "bobcontent1") and a common CSS class name to group them together (ie: "switchgroup1"). Then for each content's corresponding header, assign it the same ID as the content itself, but suffixed with "-title" (ie: "bobcontent1-title"). This conversion lets the script know what belongs to what.

Warning: The tags used to act as the content headers (ie: "bobcontent1-title") must be a container tag itself, whether H1, H2, P, DIV, SPAN etc. If you wish to use images as the content headers, wrap it inside a container tag, for example:

<span id="bobcontent1-title" class="handcursor"><img src="header.gif" /></span>

Step 2: Once your switch contents are defined, you're ready to make them expandable/ contractible, by declaring the JavaScript invocation code following it:

<script type="text/javascript">
var bobexample=new switchcontent("switchgroup1", "div") //Limit scanning of switch contents to just "div" elements
bobexample.setStatus('<img src="open.png" /> ', '<img src="close.png" /> ')
bobexample.setColor('darkred', 'black')
bobexample.setPersist(true)
bobexample.collapsePrevious(true) //Only one content open at any given time
bobexample.init()
</script>

And that's the gist of it, but wait...

Using Ajax to specify remote content for certain headers

You can specify an external file as the content of any header within a Switch Content group, so that the content is fetched on demand only when the header is actually expanded (either automatically or by user action). To do this, you'll probably want to first empty out any inline content that exists for the given header(s), for example:

<h3 id="bobcontent1-title" class="handcursor">What is JavaScript?</h3>
<div id="bobcontent1" class="switchgroup1">
<!--Nothing here-->
</div>


<h3 id="bobcontent2-title" class="handcursor">Difference between Java & JavaScript?</h3>
<div id="bobcontent2" class="switchgroup1">
<!--Nothing here-->
</div>

Then, within your invocation code of Step 2, dynamically assign an external file to the 1st and 2nd headers above, by calling the setContent() function:

<script type="text/javascript">
var bobexample=new switchcontent("switchgroup1", "div") //Limit scanning of switch contents to just "div" elements
"
"
bobexample.setContent(0, 'whatisjavascript.htm') //specify remote content for 1st header's content
bobexample.setContent(1, 'whatisjava.htm') //specify remote content for 2nd header's content

bobexample.init()
</script>

And there you have it.

Documentation

Here's a detailed explanation of what each line does, some of which are optional:

Methods for switchcontent() object
Method Description
new switchcontent("classname",
"[optional_element_type]")

Required

Main Switch Content object function that sets up contents with a shared CSS class name to be switch contents.

Parameters:

  • className: CSS class name of the content containers in this group.
  • optional_element_type: Limits the script to scanning only this type of element (ie: "div") when looking for your switch contents (ones with a shared CSS classname). Optional, and if parameter is not defined, the script will scan all elements on the page (less efficient).

    So lets say all your switch contents are paragraphs. Enter "p" to help the script run quicker by only scanning paragraphs on the page for any switch content. However, if your switch contents are a mix of more than 1 types of element, do not set this parameter:

    var samplegroup=new switchcontent("group1")
instance.setStatus(openHTML, closedHTML) Sets HTML that's added in front of each header to indicate its content's expand/contract status.

Parameters:

  • openHTML: HTML to show to indicate content is expanded.
  • closedHTML: HTML to show to indicate content is contracted.
instance.setColor(openheaderColor, closedheaderColor) Sets the header's color (if it's text based) depending on whether its content is expanded or contracted.

Parameters:

  • openheadercolor: Color of header when its content is expanded.
  • closedheadercolor: Color of header when its content is contracted.
instance.setContent(index, filepath) New Allows you to specify an external file as the corresponding content for a header. Call this function multiple times to specify Ajax content for multiple headers.

Parameters:

  • index: The index of the header to specify Ajax content for relative to the rest of the headers (starts at 0)
  • filepath: The path to the external content on your server relative to the current page.

The remote content is only fetched when the header is expanded, and only once. So if all your headers are Ajax based and contracted by default, none of the remote contents are fetched until the header in question is expanded. Contracting then expanding the same header again won't cause the content to be fetched again.

Examples:

instance.setContent(0, 'external.htm') //Ajax content for 1st header within group
instance.setContent(1, 'external2.htm') //Ajax content for 2nd header within group

instance.setPersist(Boolean, [days]) Enables or disables persistence, so the state of the contents is remembered either for the browser session or x days. A browser session is defined as until the user closes the browser.

Parameters:

  • Boolean: True or false
  • days: An optional integer that specifies the number of days to persist the content states (applicable only if 1st parameter is set to true). Defining this parameter switches the persistence type from session only to the desired number of days instead.

Examples:

instance.setPersist(false) //No persistence
instance.setPersist(true) //Enable session-only persistence
instance.setPersist(true, 7) //Set persistence to 7 days

instance.collapsePrevious(Boolean) Specifies whether any previously expanded content should be contracted first before expanding the current one, effectively specifying that only one content can be open at any time.

Parameter:

  • Boolean: True or false
instance.defaultExpanded(indices) By default, the script will contract all contents within a switch group when the page first loads. Use this method to specify those contents that should be expanded by default, by entering their index (position) relative to the other contents inside the group, each separated by a comma (,).

Parameter: Indices of the contents to be expanded by default relative to the rest of the contents (starts at 0). A few examples:

instance.defaultExpanded(0) //1st content expanded
instance.defaultExpanded(0,1) //1st and 2nd content expanded
instance.defaultExpanded(3,5) //3rd and 5th content expanded

Exceptions: Two conditions if met will override this setting:

  1. If setPersist() is enabled, the persisted states takes precedence.
  2. If collapsePrevious() is enabled, then only the first content set to expand by default will be expanded, as collapsePrevious() means only one content can be open at any given time.
instance.init()

Required

Call this function at the very end to initialize the Switch Content group using the above settings.

And just for reinforcement, here's the JavaScript invocation code for the 2nd demo you see at the beginning of the page:

<script type="text/javascript">

var joeexample=new switchcontent("switchgroup2", "p")
joeexample.setStatus('[open] ', '[closed] ')
joeexample.setColor('green', 'red')
joeexample.collapsePrevious(false) //Allow more than 1 content to be open simultanously
joeexample.setPersist(false)
joeexample.defaultExpanded(0,1) //1st and 2nd contents within group should be expanded by default
joeexample.setContent(0, 'whatisjavascript.htm') //specify remote content for 1st header's content
joeexample.setContent(1, 'whatisjava.htm') //specify remote content for 2nd header's content
joeexample.init()
</script>

Have fun! But before we go, if you want to define manual links on the page to instantly contract or expand all contents within a Switch group, use the below method within your HTML code:

instance.sweepToggle('contract/expand') Contracts or expands all contents within a Switch group.

Parameter: "contract" or "expand".

Example:

<div>
<a href="javascript:joeexample.sweepToggle('contract')">Contract All</a>
<a href="javascript:joeexample.sweepToggle('expand')">Expand All</a>
</div>

Ok now we're really done. :-)