Created
August 17, 2012 16:51
-
-
Save oomlaut/3380508 to your computer and use it in GitHub Desktop.
Text Summary jQuery Plug-in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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