Wednesday, September 9, 2009

jQuery function to truncate long text

The scenario: You have some text that is too long in for example a textarea and want to be able to truncate it client-side and only display a maximum amount of characters. You also want to add the ability for the user to dynamically expand the text by clicking the "more..." link appended to the text.

The concern: This is not Ajax enabled and the entire text is rendered to the client and the text extending beyond the maximum is hidden. If the text you want to hide is very large it may suffice the rather extend this function to make an Ajax call that will fetch the rest of the text.


The application: Can be used to limit the amount of text displayed to the user for the textarea, paragraph, div, etc. It is not intended to hide large amount of text that would result in unacceptable download times to the user.

(function($) {

$.fn.TruncExpandText = function(options) {
var defaultVals = {
maxLength: 500,
setLength: 500,
heightOfContainer: '108px',
text: 'more...'
};

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

})(jQuery);

function TruncateTextForTextareaAndAttachMoreEventToExpand($item, defaultVals) {
if (defaultVals == null) {
defaultVals = {
maxLength: 1000,
setLength: 1000,
heightOfContainer: '220px',
text: '...'
};
}
return $item.each(function() {
//Cut long text and add more...
$(this).each(function() {
var $me = $(this);
var $newOne = $(this).clone().addClass('crm_more');
$(this).after($newOne);
$(this).remove();
if ($newOne.val().length > defaultVals.maxLength) {
var val = $(this).val();
$newOne.val(val.substring(0, defaultVals.setLength)).css({ height: defaultVals.heightOfContainer }).after('' + defaultVals.text + '').next().click(function() {
$(this).prev().val(val);
var $parent = $(this).prev();
$parent.autogrow({ expandTolerance: 1 });
$(this).remove();
}).attr({ title: 'Click to see all the comments' }).css({ cursor: 'pointer' });
}
});
});
}

This is how to use it:

Defaulted to truncate after 500 characters:

$('.textThatneedsToBeTruncated').TruncExpandText();

Truncates after 1500 characters:

$('.textThatneedsToBeTruncated').TruncExpandText({maxLength: 1500});

Sets the length of the text item that exceeds 500 characters to display 800 characters:

$('.textThatneedsToBeTruncated').TruncExpandText({setLength: 800});

Sets the text of the hint/link to "click to see all text...":

$('.textThatneedsToBeTruncated').TruncExpandText({text: 'click to see all text...'});

Sets the max length to 50 and the text to "...":

$('.textThatneedsToBeTruncated').TruncExpandText({maxLength: 50, text: '...'});

No comments:

Post a Comment