JSFiddle - React, Tailwind, and code Playground
by Peter Galiba
HTML
<ul>
<li><a href="" id="id-1">Item 1</a></li>
<li><a href="" id="id-2">Item 2</a></li>
<li><a href="" id="id-3">Item 3</a></li>
<li><a href="" id="id-4">Item 4</a></li>
</ul>
CSS
.element-hidden {
display: none;
}
JavaScript
/**
* @file
* Customizations for the article pages.
*/
(function ($, document) {
var punctations = /[.!?\u00a1\u203c\u2026\u00bf\u203d]\s|\u3002/,
wordDelim = /\s/,
truncateDefaults,
truncatedDefaults,
fn = $.fn;
/**
* Truncate the text in a node to a specific size, closing the last sentence.
*
* @param {Node} node
* The node to truncate the text in.
* @param {Number} maxLength
* The length of the string after to search the end of the sentence.
* @param {Object} settings
*
* @return
* Object with the following fields:
* - text: Contains the truncated text.
* - node: The last non-text node that was parsed.
*/
function truncate(nodes, maxLength, settings) {
var text = '', // Current text
searching = 1, // Is the search in progress.
lastNode, // Last node that was checked
sentenceSafe = settings.sentenceSafe,
wordSafe = settings.wordSafe,
checkDelim = sentenceSafe || wordSafe,
regex = sentenceSafe ? punctations : wordDelim;
// Go through the nodes to find maxLength text plus the next puctation.
(function getText(elems) {
var elem, // Current DOM element to check.
i = 0, // Iteration variable
result; // Results of the regex execution.
for (; elems[i] && searching; i += 1) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes.
if (elem.nodeType === 3 || elem.nodeType === 4) {
// Trim the value if the text is still empty.
text += text ? elem.nodeValue : elem.nodeValue.replace(/^\s+/, '');
// Check if the text is enough.
if (text.length >= maxLength) {
if (checkDelim) {
result = regex.exec(text.slice(maxLength));
if (result) {
text = text.slice(0, maxLength + result.index + (wordSafe ? 0 : 1));
searching = 0;
}
...