Skip to content

Instantly share code, notes, and snippets.

@oomlaut
Created August 17, 2012 16:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oomlaut/3380508 to your computer and use it in GitHub Desktop.
Save oomlaut/3380508 to your computer and use it in GitHub Desktop.
Text Summary jQuery Plug-in
$.fn.textSummary = function (options, callback) {
var settings = {
maxlength: 150,
morechar: "…"
};
$.extend(true, settings, options);
return this.each(function () {
var $context = $(this).hide().append($('<a>', {
"class": "showless",
href: "#",
text: "(less)",
click: function (e) {
e.preventDefault();
$context.hide();
}
}));
var contentChunks = $context.html().split(' ');
var summarytext = new String();
var exceeded = false;
$.each(contentChunks, function (i, v) {
if ((summarytext.length + v.length <= settings.maxlength) && !exceeded) {
if (i > 0) {
summarytext += ' ';
}
summarytext += v;
} else {
exceeded = true;
}
});
var $summary = $('<p>', {
"class": "announcement-summary"
}).html(summarytext + settings.morechar).insertBefore($context);
if ($context.html().length > settings.maxlength) {
$summary.append($('<a>', {
"class": "showmore",
href: "#",
text: "(more)",
click: function (e) {
e.preventDefault();
$context.show();
}
}));
}
if ($.isFunction(callback)) { callback(); }
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment