Here is my solution:

The HTML structure of each DIV:

<div class="article">
    <p>
        Basic content
    </p>
    <p class="details">
        Additional content
    </p>
</div>

The JS code:

// the clickable "more details" SPAN element (as a string)
var $showMore = " <span class='showMore'>More Details</span>";

// the function that hides the second P, and adds the SPAN to the
first P
function hideDetails(div) {
        $(div)
            .find("p:first").append($showMore)
            .end().find(".details").hide();
}

$(document).ready(function() {

    // do the initialization for every DIV with class ".articles"
    $(".article").each(function() { hideDetails(this); });

    // attach a live click event handler to every "more details" SPAN
element
    $(".showMore").live("click", function() {
        $(this).closest(".article").find(".details").slideToggle(400);
        $(this).text($(this).text() == 'More Details' ? 'Close' :
'More Details');
    });

});

Because the handler was attached to an live event, you can now
dynamically create DIVs, for example:

$("<div class='article'></div>")
        .append("<p>Another basic content<p>")
        .append("<p class='details'>Another additional content</p>")
        .appendTo("body")
        .each(function() { hideDetails(this); });

This solution works in the way that if JS is turned off, the second P
will be visible, and there will be no "More details" SPAN.



Reply via email to