This repository was archived by the owner on Jun 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.limitText.js
More file actions
74 lines (65 loc) · 2.08 KB
/
jquery.limitText.js
File metadata and controls
74 lines (65 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*******************************************************************************
JQuery plugin to create a "Read More" section for dynamically populated text by limiting the number of visible characters.
Version 0.1 - July 5, 2015
Customizable options:
characterLimit: 240,
readLessText: "Read Less",
readMoreText: "Read More",
showEllipsis: true
*******************************************************************************/
(function($) {
$.fn.limitText = function (userOptions) {
this.each(function() {
var defaultOptions = {
characterLimit: 240,
readLessText: "Read less",
readMoreText: "Read more",
showEllipsis: true
};
var options = $.extend({}, defaultOptions, userOptions);
var expander = $(this);
var fullHtml = expander.html();
var fullText = expander.text();
if (fullText.length > options.characterLimit) {
// Limit number of characters in text, word by word
var fullWordList = fullText.split(/\s+/);
var shortText = "";
while ((shortText + fullWordList[0] + " ").length < options.characterLimit) {
shortText += fullWordList.shift() + " ";
}
if (options.showEllipsis) { shortText += "... "; }
// Clear existing content
$(this).html("");
// Add short text and "Read more" toggle
var expanderShort = $("<div/>", {
class: "text-short",
text: shortText
});
var expanderShortToggle = $("<a/>", {
class: "toggle",
text: options.readMoreText
});
expanderShort.append(expanderShortToggle);
expander.append(expanderShort);
// Add back full text and "Read less" toggle
var expanderFull = $("<div/>", {
class: "text-full",
html: fullHtml + " "
});
var expanderFullToggle = $("<a/>", {
class: "toggle",
text: options.readLessText
});
expanderFull.append(expanderFullToggle);
expander.append(expanderFull);
}
});
// Toggle more/less text functionality
$(".text-short").show();
$(".text-full").hide();
$(".toggle").click(function(){
$(this).parent().hide();
$(this).parent().siblings().show();
});
}
}(jQuery));