Dynamic Show "More" and "Less" Link using jQuery

Here is one useful jQuery functionality to dynamically showing option for hiding some parts of large text with the option for show more link.

I.e. If the comment text is larger than few characters, the extra words are hide and a show more link is presented to user.

HTML:

<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.
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;
}

jQuery :

$(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-1, 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;
});
});


Please find the working sample page attached along with the article. Give a try!!

Thanks
Shinu