When your website means business.

jQuery | Type: JavascriptRead More/Less Toggle

Not as easy to find as I’d have guessed. Initially shows a defined number of characters (appended with ellipses) and a ‘read more’ link. One issue: if a word is split by character count, there is a space inserted in the middle of the word (where split occurred) when ‘Read more’ is clicked.


HTML
<p class="toggle-text">Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi. Molestias sapiente ad similique animi magnam necessitatibus, qui amet expedita, molestiae facere.</p>

CSS
.toggle-text { }
.toggle-text-content span { display: none; }
.toggle-text-link { display: inline; }

jQUERY
    // Show more text option -campaing page
    var showChar = 196;  // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Read more";
    var lesstext = "Read less";
    
    //Cut content based on showChar length
    if ($(".toggle-text").length) {
        $(".toggle-text").each(function() {

            var content = $(this).html();
     
            if(content.length &gt; showChar) {
     
                var contentExcert = content.substr(0, showChar);
                var contentRest = content.substr(showChar, content.length - showChar);
                var html = contentExcert + '<span class="toggle-text-ellipses">' + ellipsestext + ' </span> <span class="toggle-text-content">' + contentRest + '<a class="btn btn--primary btn--dark toggle-text-link">' + moretext + '</a></span>';
     
                $(this).html(html);
            }
        });
    }
    
    //Toggle content when click on read more link
    $(".toggle-text-link").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });

Reference Links

Menu
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Cookies Notice