jQuery Toggle

I needed a quick toggle for a jQuery powered site that does not have a full featured CMS, has older version of jQuery, don’t have access to the hosting environment. Luckily, I am able to edit the source in the WYSIWYG editor. This solution seemed to work well…

<script type=”text/javascript”>
$(document).ready(function() {
$(“.answer”).hide();
$(“.question”).click(function()
{
$(this).next(“.answer”).slideToggle(500);
});
});

</script>

(Originally found over at designgala.com)

This is an example of how I structured the content

<p class=”question” title=”Click to Expand”><strong>This is the question</strong></p>
<p class=”answer”>This is the answer to the previously asked question</p>

I ended up having to extend the script a little as I wanted the cursor style to change when a user hovered over the question. I did this by adding the following to the previous script.

$(“.question”).hover(function()
{
$(this).css(‘cursor’,'pointer’);
}, function() {
$(this).css(‘cursor’,'auto’);
});

So the final in body script looked like this:

<script type=”text/javascript”>
$(document).ready(function() {
$(“.answer”).hide();
$(“.question”).click(function()
{
$(this).next(“.answer”).slideToggle(500);
});

//Add cursor styling
$(“.question”).hover(function()
{
$(this).css(‘cursor’,'pointer’);
}, function() {
$(this).css(‘cursor’,'auto’);
});
});
</script>

Seemed to work well for what we were looking to implement. You could extend this with CSS, adding images or even additional elements from the jQuery UI