Show more/show less functionality with jQuery

I looked at the code at jQuery More/Less Text and I think this is a pretty good solution. Depending on the height of the box, the contents either hide the overflow and show a “Show More” button or they show the overflow and show a “Show Less” button.

The post by Stu Green also shows how to hide this button when contents fit into the box. However, I need to explain how to do this yourself. Your HTML should be:

<div class="showmore">
    <div class="moreblock">
    	<p>The Content</p>
    </div>
</div>

Your JS function should be:

function showMore() {
    // The height of the content block when it's not expanded
    var adjustheight = 55;
    var moreText = "Read more...";
    var lessText = "Read less...";

    $(".showmore > .moreblock").each(function(){
        if ($(this).height() > adjustheight){
            $(this).css('height', adjustheight).css('overflow', 'hidden');
            $(this).parent(".showmore").append('<p class="continued">&hellip;</p><a href="#" class="adjust"></a>');
            $(this).parent(".showmore").find("a.adjust").text(moreText);
            $(this).parent(".showmore").find(".adjust").toggle(function() {
                $(this).parents("div:first").find(".moreblock").css('height', 'auto').css('overflow', 'visible');
                $(this).parents("div:first").find("p.continued").css('display', 'none');
                $(this).text(lessText);
            }, function() {
                $(this).parents("div:first").find(".moreblock").css('height', adjustheight).css('overflow', 'hidden');
                $(this).parents("div:first").find("p.continued").css('display', 'block');
                $(this).text(moreText);
            });
        }
    });
}

then you just call showMore() somewhere. Usually it will be when the document is ready, but sometimes you’ll do this in the callback after dynamically loading content. I hope this helps.

https://www.cityblis.com/ uses a similar approach ported to the newest jQuery (toggle has been deprecated)

About these ads

3 responses to “Show more/show less functionality with jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s