Monday, September 17, 2012

Show More /Less link using jQuery

Sample text:
<div class="comment more">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Vestibulum laoreet, nunc eget laoreet sagittis,
    quam ligula sodales orci, congue imperdiet eros tortor ac lectus.
    Duis eget nisl orci. Aliquam mattis purus non mauris
    blandit id luctus felis convallis.
    Integer varius egestas vestibulum.
    Nullam a dolor arcu, ac tempor elit. Donec.
</div>
 
 
CSS: 

a {
    color: #0254EB
}
a:visited {
    color: #0254EB
}
a.morelink {
    text-decoration:none;
    outline: none;
}
.morecontent span {
    display: none;
}
.comment {
    width: 400px;
    background-color: #f0f0f0;
    margin: 10px;
}
 
Javascript:
$(document).ready(function() {
    var showChar = 100;
    var ellipsestext = "...";
    var moretext = "more";
    var lesstext = "less";
    $('.more').each(function() {
        var content = $(this).html();
 
        if(content.length > showChar) {
 
            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);
 
            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
 
            $(this).html(html);
        }
 
    });
 
    $(".morelink").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;
    });
});
 

2 comments:

  1. Hi, very interesting article but unfortunately not sure how to apply it in real life. would be nice if you had guides on which file to modify etc. thanks!

    ReplyDelete
    Replies
    1. hey, this is not related to any file. You can use in any large test message showing on site.

      Delete