Split paragraph and add read more button with Javascript

Obada Qawwas
in - Javascript

Read more button

If you want to create a read more button that extends a paragraph already being shown to reveal the entire text on the same page. I’ve made a simple javascript function that can handle this job, I will put here the JS code and you can download the whole thing by pressing on the download button up in the corner 🙂

The Javascript function:

function readMore(){
    var base = this,
        container = $(".entry-item .entry-item-content");

    /* select all divs with the shorten-text class */
    container.each( function(event) {

        /* set the max content length before a read more link will be added */
        var max_length = ( $(this).parent().data('text-length') ) ? parseInt( $(this).parent().data('text-length'), 10 ) : 600;

        /* check for content length */
        if($(this).find(".editor").html().length > max_length){

            /* split the content in two parts */
            var short_content   = $(this).html().substr( 0, max_length );
            var long_content    = $(this).html().substr( max_length );

            /* Alter the html to allow the read more functionality */
            if ( long_content.length > 400 ) {
                var self;
                self = $(this);

                $(this).html("");
                $(this).append(short_content   '<span class="three-dots">...&nbsp;&nbsp;</span>');
                $(this).append('<a href="#" class="read-more">Read More</a>');

                /* find the a.read-more element within the new html and bind the following code to it */
                $(this).find('a.read-more').click( function(event){

                    /* prevent the <a> from changing the url */
                    event.preventDefault();

                    $(this).closest(".entry-item-content").addClass("active");

                    self.html("");
                    self.append(short_content   long_content);

                    /* hide the read-more button */
                    $(this).hide();
                    $(".three-dots").hide();
                    /* show the .more-text span */
                    $(this).parent().find('.more-text').show();

                });
            }
        } else {
            container.addClass("show-footer");
        }

    });
}
Screenshot:
Split paragraph and add read more button with Javascript
References & Credits:

Photo by Ashim D’Silva on Unsplash

Please enable Javascript in order to post comments.