Thursday 23 August 2012

Concertina - reveal and hide text by click

In our SharePoint 2007 site collection we've had quite a few requests for FAQs that open when the question is clicked then snap shut when the question is clicked again. This is a fairly simple effect to achieve in a Data View Web Part.


To contain the FAQ questions and answers, create a custom list and add a single additional multi-line text column, Answer, to hold the answers. You'll use the Title column to hold the questions. If you expect the FAQs to divide into sections, you can another field called Category, perhaps as a Choice field, and add your categories as choice values.

Now add one or two questions and answers (and if applicable, assign a Category value to each q&a) so you'll be able to see content as you build your Data View Web Part.

Next, create a Data View Web Part on the appropriate page and insert data from the fields Title and Answer.

Finally, replace the table-row that's displaying your list data in the DVWP with this code:

    <xsl:if test="position() = 1">
     <tr>
      <td>
       <h2><xsl:value-of select="@Category"/></h2>
      </td>
     </tr>
     </xsl:if>
     <tr>
      <td class="ms-vb"><span style="cursor:pointer" onclick="if (this.parentNode.parentNode.nextSibling.style.display=='none') this.parentNode.parentNode.nextSibling.style.display='block'; else this.parentNode.parentNode.nextSibling.style.display='none';" >
       <h3 style="margin:0px"><img src="/masterPageTemplateImages/miniplus.gif" />&#x9;<xsl:value-of select="@Title" /></h3></span></td>
 
     </tr>
     <tr style="display:none">
      <td class="ms-vb">
       <xsl:value-of select="@Answer" disable-output-escaping="yes" /></td>
 
     </tr>
     <tr><td><img src="/masterPageTemplateImages/spacer.gif" height="10" width="50"/></td></tr>


The "miniplus.gif" image is optional, but helps clarify for the users that the question is clickable to reveal the answer and the final table cell with the spacer.gif just adds a little space between the q&as.

That's it - job done!