toggleAnswers

by jorgeluis

HTML

<dl class="faq list-toggled">
    <dt><span class="icon icon-arrow closed"></span>Is this a common FAQ?</dt>
    <dd>Sometimes it's best to hide the answers to save screen space. Users would click on the question to see the answer. Always make sure there's a visual way to indicate that the question is clickable.</dd>

    <dt><span class="icon icon-arrow closed"></span>Is this a common FAQ?</dt>
    <dd>Sometimes it's best to hide the answers to save screen space. Users would click on the question to see the answer. Always make sure there's a visual way to indicate that the question is clickable.</dd>

    <dt><span class="icon icon-arrow closed"></span>Is this a common FAQ?</dt>
    <dd>Sometimes it's best to hide the answers to save screen space. Users would click on the question to see the answer. Always make sure there's a visual way to indicate that the question is clickable.</dd>
</dl>

CSS

dt { cursor: pointer; margin: 1em 0 .3em; color: blue }
.icon-arrow {
    padding: 2px 10px;
}
.icon-arrow.closed {
    background: transparent url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAM0lEQVQYV2NkAIIzZ878NzExYQSxsQG4BD6FKLpxKcSwAptCrO5AV0i6SQTdRNB3hMIJAA0iJAr617J4AAAAAElFTkSuQmCC) no-repeat;
}
.icon-arrow.opened {
    background: transparent url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAOElEQVQYV2NkIAIwnjlz5r+JiQkjLrUgebAkLoUwcbgJ6AqR+SjWwCTQNWC4BZvVOB2M7BHqKQIAGzUjbcaDZioAAAAASUVORK5CYII=) no-repeat;
}

JavaScript

(function () {
    var qList = $('dl.list-toggled');
    var answers = qList.find('dd').hide();
    var question = qList.find('dt').each(function(){
        $(this).toggle(
        function(){
            $(this).next('dd').slideDown('fast');
            $(this).find('.icon-arrow').removeClass('closed').addClass('opened');
        },
        function(){
            $(this).next('dd').slideUp('fast');
            $(this).find('.icon-arrow').removeClass('opened').addClass('closed');
        }
        )
    });
})();