jQuery: shorten paragraphs and create a "Read More" link

jQuery: shorten paragraphs and create a "Read More" link

Creating excerpts from paragraphs and adding a "Read More" link to them with jQuery.

jQuery is able to manipulate the text content of any HTML element very easily. For example, we can shorten paragraphs to a certain length and show a "Read More" link that will restore the original text. Let's see how to accomplish this task.

The only thing to consider carefully is where to store the original full text of each paragraph. We can use the data() method to cache our text and then restore it when needed:

var shortenP = function(options) {

    options = $.extend({
        length: 160,
        ellipsis: ' [...]',
        moreClass: 'more-link',
        moreText: 'Read More'
    }, options);

    $('p').each(function() {

        var $p = $(this);
        var text = $p.text();
        var shortString = text.substring(0, options.length) + options.ellipsis;
        $p.data('fulltext', text);
        $p.text(shortString);
        $('<a/>').attr({
            href: '#',
            'class': options.moreClass
        }).text(options.moreText).
        insertAfter($p);
        $p.next().click(function(e) {

            $p.text($p.data('fulltext'));
            e.preventDefault();
        });

    });

};

shortenP();

Our function accepts options just like a normal jQuery plugin. We simply loop through all the paragraph set and we shorten each paragraph's text by using the core JavaScript substring() method.

We store the original text on the paragraph element by caching it with data(). Then we create an HTML link and we insert it just after the current paragraph. When a user clicks on the link, the original text is restored.

You can see the demo below.

Demo

Live demo