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 II (icon based)

Author: Dynamic Drive

Note:

  • Requires switchcontent.js from Switch Content Script I.
  • March 27th, 08': Added ability for certain headers to get its contents remotely from an external file via Ajax. Both switchcontent.js and switchicon.js changed!

Description: Switch Content Script II is a flexible script that adds contact/expand functionality to arbitrary block content on a page using a simple "icon" to toggle its state. You may have seen something similar used on sites such as Microsoft.com. It lets the viewer choose which content on the page to contract, to remove unnecessary clutter. An image icon is used to toggle between states when clicked on and to show the current state of the content. And to complete the experience, permanent cookies are used to remember the content states so they are retained even when the user leaves then returns to the page three days from now, for example. Did we miss anything? :)

  • Works unobtrusively in all modern browsers. Those with JavaScript disabled will simply see all the contents expanded by default.
  • Specify your own toggling icon to place anywhere on the page to expand/ contract a content. The icon is simply a SPAN tag.
  • 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.
  • 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.
  • Supports persistence of content states using session or non-session cookies (in days), 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.

Switch Content II (this script) is powered bythe original Switch Content I script. Both utilize the same core file "swithcontent.js", although the former also includes "switchicon.js" to give it the modified behavior of using icons instead of regular headers to switch contents.

Demo 1: Contract All | Expand All

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 between 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 combining of HTML, CSS, and JavaScript.

  Demo 2:

How hot is our Sun?
The surface of the Sun is around 5800 Kelvin, while the core reaches over 15 million Kelvin.
How big is our Sun in terms of mass?
The contains more than 99.8% of the total mass of our Solar System.

Notes for demo #1:
  • Two images are used as the toggling icon.
  • "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 disabled.
 

Notes for demo #2:
  • The text "[hide]" and "[show]" are used for the toggling icon.
  • No contents set to open by default (overridden by cookie setting, if available).
  • Persistence feature enabled to remember content states for 7 days.

Directions: Developer's View

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

Select All

The code references two external .js files, 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 icons to participate in the "switching". For example:

What is JavaScript? <span id="faq1-title" class="iconspan"><img src="minus.gif" /></span>
<div id="faq1" class="icongroup1">
JavaScript is a scripting language originally developed by Netscape to add interactivity and power to web documents.
</div>

What is DHTML? <span id="faq2-title" class="iconspan"><img src="minus.gif" /></span>
<div id="faq2" class="icongroup1">
DHTML is the embodiment of a combination of technologies
</div>

Here I have two contents plus the icons to toggle their states using. The only protocol you must follow is to give each content container a unique ID (ie: "faq1") and a common CSS class name to group them together (ie: "icongroup1"). Then for each content's corresponding icon, define a SPAN tag with the same ID as the content itself, but suffixed with "-title" (ie: "faq1-title"). Inside this SPAN tag you define the HTML for the icon itself, such as an image.

Step 2: Once your switch contents are defined following the above convention, you're ready to make them expandable/ contractible, by calling a piece of JavaScript following it:

<script type="text/javascript">

var faq=new switchicon("icongroup1", "div") //Limit scanning of switch contents to just "div" elements
faq.setHeader('<img src="minus.gif" />', '<img src="plus.gif" />') //set icon HTML
faq.collapsePrevious(true) //Allow only 1 content open at any time
faq.setPersist(false) //No persistence enabled
faq.defaultExpanded(0) //Set 1st content to be expanded by default
faq.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:

What is JavaScript? <span id="faq1-title" class="iconspan"><img src="minus.gif" /></span>
<div id="faq1" class="icongroup1">
<!--Nothing here-->
</div>

What is DHTML? <span id="faq2-title" class="iconspan"><img src="minus.gif" /></span>
<div id="faq2" class="icongroup1">
<!--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 faq=new switchicon("icongroup1", "div") //Limit scanning of switch contents to just "div" elements
"
faq.setContent(0, 'whatisjavascript.htm') //specify remote content for 1st header's content
faq.setContent(1, 'whatisjava.htm') //specify remote content for 2nd header's content

faq.defaultExpanded(0) //Set 1st content to be expanded by default
faq.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.setHeader(openHTML, closedHTML) Sets the HTML of the icon depending on whether its associated content is expanded or contracted.

Parameters:

  • openHTML: HTML to use as the icon to indicate content is expanded.
  • closedHTML: HTML to use as the icon to indicate content is contracted.

Examples:

instance.setHeader('<img src="close.gif" />', '<img src="open.gif" />')
instance.setHeader('[opened]', '[closed]') //regular text icon instead

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 faqtable=new switchicon("icongroup2", "div") //Limit scanning of switch contents to just "div" elements
faqtable.setHeader('[Hide]', '[Show]') //Set header HTML
faqtable.collapsePrevious(false) //Allow more than 1 content to be open simultanously
faqtable.setPersist(true, 7) //Enable persistence to remember last switch content states for 7 days
faqtable.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:faqtable.sweepToggle('contract')">Contract All</a>
<a href="javascript:faqtable.sweepToggle('expand')">Expand All</a>
</div>

Ok now we're really done. :-)