Online Promoters™ :: Web Development made simple

Limit text with jQuery – text limiting – show more …

I needed to limit some longer texts on one of the sites I currently develop and I came with the following solution. I started from the original script made by Renso Hollhumer.
If you do improve this script please write a comment with your link to the page where you have posted it.

You put this in : text_limit_plugin.js
[sourcecode language="js"]
(function($) {

$.fn.TruncExpandText = function(options) {
var defaultVals = {
maxLength: 500,
setLength: 500,
heightOfContainer: 'auto',
text_more: 'more...',
text_less: 'less...',
class_name: 'crm_more'

return this.each(function() {
TruncateText($(this), $.extend({}, defaultVals, options));


function TruncateText($item, defaultVals) {
return $item.each(function() {
$(this).each(function() {
var $me = $(this);
var $newOne = $(this).clone()
var $class = defaultVals.class_name;
if ($newOne.text().length > defaultVals.maxLength)
var field_type = this.tagName;
var val = $(this).val();
$newOne.val(val.substring(0, defaultVals.setLength)).css({ height: defaultVals.heightOfContainer }).after('<span class="'+$class+'">' + defaultVals.text_more + '</span>').next().click(function() {
var $parent = $(this).prev();
$parent.autogrow({ expandTolerance: 1 });
}).attr({ title: defaultVals.text_more }).css({ cursor: 'pointer' });
var val = $(this).text();
var trimed_text = val.substring(0, defaultVals.setLength);
$newOne.text(trimed_text).css({ height: defaultVals.heightOfContainer }).after('<span class="'+$class+'">' + defaultVals.text_more + '</span>').next().attr({ title: defaultVals.text_more }).css({ cursor: 'pointer' }).toggle(
var $parent = $(this).prev();
}, function(e,el)
$parent = $(this).prev();



You put this in your css file:
[sourcecode language="css"]
font-style: italic;
font-weight: bold;
font-size: .9em

You limit the text by applying it a class name like this:
[sourcecode language="html"]
<div class="limitare">Your Looonnnnggg text!</div>
<script type="text/javascript">$('.limitare').TruncExpandText({maxLength: '200', text_more: 'mai mult...',text_less: 'mai putin...'}); </script>

maxLength - the number of chars you want to limit the text
text_more - the "more" text
text_less - the "less" text

This is my best way until today®. If I missed something out please let me know!