Tuesday, May 5, 2009

Show/Hide a chunk of text

A pretty common task that I do a lot is provide the user the ability to show and hide a chunk of text. For example, say I have a page containing a list of songs and I want to allow the user the ability to see and hide the lyrics of the song. The format could potentially be the song title with a "show lyric" link beside it that when clicked will reveal the lyrics below it in a "Ajaxed" slidedown. The 'Show lyrics' text could then change to 'hide lyrics' which when clicked does the opposite effect.

To do this is actually pretty easy. I will be utilizing the scripaculous AJAX libraries.

To get started, you'll need to download the libraries and then include the javascript libraries into your page:



Now this next section gets a little complicated because I am using the Smarty libraries to help me abstract PHP code from my HTML layout. So bear with me:



How it works is we'll have an array of Xataface Records of the songs table. So I will be iterating through this array displaying the title and then displaying the lyrics in the song_item{$item} div id. The reason why I need to use the {$item} variable is because each id has to be unique so that when we click the link to show/hide the lyrics it knows exactly which div element to show. Notice that the onclick handler is to a javascript function called showHideLyrics() with the parameter 'song_item{$item}'. Also important is the id of the anchor link which is 'song_item{$item}_link' This is important so that we can change the anchor link text.

So the showHideLyric() javascript function:



So the first parameter is the div element containing the lyrics. We will check if it is already hidden, and if it is then we want to show it. We will rely on the scriptaculous code to do this for us. And then after that we will use the code:

document.getElementById(element + '_link').firstChild.data = "[Hide Lyrics]";


To change the anchor link text. The use of the firstChild.data properties is proper javascript. We could have used the innerHTML proper, but that is not proper. And the case is nearly the same when the lyrics are shown we just use the scriptaculous code to help us hide it and change the text to "[Show Lyrics]".

Cool hey?

No comments: