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

})(jQuery);

function TruncateText($item, defaultVals) {
return $item.each(function() {
$(this).each(function() {
var $me = $(this);
var $newOne = $(this).clone()
var $class = defaultVals.class_name;
$(this).after($newOne).addClass($class);
$(this).remove();
if ($newOne.text().length > defaultVals.maxLength)
{
var field_type = this.tagName;
if(field_type=='INPUT')
{
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() {
$(this).prev().val(val);
var $parent = $(this).prev();
$parent.autogrow({ expandTolerance: 1 });
$(this).remove();
}).attr({ title: defaultVals.text_more }).css({ cursor: 'pointer' });
}
else
{
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(
function()
{
$(this).text(defaultVals.text_less);
var $parent = $(this).prev();
$parent.fadeOut().fadeIn().text(val);
}, function(e,el)
{
$(this).text(defaultVals.text_more);
$parent = $(this).prev();
$parent.fadeOut().fadeIn().text(trimed_text);
});
}
}

});

});
}
[/sourcecode]

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

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>
[/sourcecode]

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!