javascript
Posted in
17058
11:17 pm, June 22, 2021
using clamp js to clamp lines of text
there is a css version of this as well but this version works in a greater range of browsers (i think)
this one is not working for me... i think the overflow elipsis is still a better option than this.
getting this error:
it seems to be working ok on the codepen demo, maybe its the version of jquery?
HTML
<div class="clamp1 mb-3">Cras vel ligula a elit pretium convallis. Nunc ac nisl nisi. Vestibulum ut ullamcorper nibh. Phasellus dictum nisi quis ullamcorper finibus. Phasellus fringilla purus ut augue varius vulputate. Nullam nec nisl dignissim, varius sem pretium, commodo orci. Cras tortor nisl, pharetra sodales lobortis a, vestibulum ut libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Pellentesque rutrum urna elit, sed cursus felis placerat efficitur. Curabitur tempor velit magna, mollis malesuada risus lacinia sed. Mauris tristique id mi et cursus. Quisque consectetur velit in lacus euismod scelerisque. Vestibulum ac malesuada libero, eget auctor turpis. Integer pellentesque a ipsum non faucibus. Quisque ultricies sapien ut tellus bibendum aliquam.</div>
<div class='clamp2 mb-3'>Cras vel ligula a elit pretium convallis. Nunc ac nisl nisi. Vestibulum ut ullamcorper nibh. Phasellus dictum nisi quis ullamcorper finibus. Phasellus fringilla purus ut augue varius vulputate. Nullam nec nisl dignissim, varius sem pretium, commodo orci. Cras tortor nisl, pharetra sodales lobortis a, vestibulum ut libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Pellentesque rutrum urna elit, sed cursus felis placerat efficitur. Curabitur tempor velit magna, mollis malesuada risus lacinia sed. Mauris tristique id mi et cursus. Quisque consectetur velit in lacus euismod scelerisque. Vestibulum ac malesuada libero, eget auctor turpis. Integer pellentesque a ipsum non faucibus. Quisque ultricies sapien ut tellus bibendum aliquam.</div>
<div class='clamp3 mb-3'>Cras vel ligula a elit pretium convallis. Nunc ac nisl nisi. Vestibulum ut ullamcorper nibh. Phasellus dictum nisi quis ullamcorper finibus. Phasellus fringilla purus ut augue varius vulputate. Nullam nec nisl dignissim, varius sem pretium, commodo orci. Cras tortor nisl, pharetra sodales lobortis a, vestibulum ut libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Pellentesque rutrum urna elit, sed cursus felis placerat efficitur. Curabitur tempor velit magna, mollis malesuada risus lacinia sed. Mauris tristique id mi et cursus. Quisque consectetur velit in lacus euismod scelerisque. Vestibulum ac malesuada libero, eget auctor turpis. Integer pellentesque a ipsum non faucibus. Quisque ultricies sapien ut tellus bibendum aliquam.</div>
Javascript
/*!
* Clamp.js 0.5.1
*
* Copyright 2011-2013, Joseph Schmitt http://joe.sh
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*/
(function(){
/**
* Clamps a text node.
* @param {HTMLElement} element. Element containing the text node to clamp.
* @param {Object} options. Options to pass to the clamper.
*/
function clamp(element, options) {
options = options || {};
var self = this,
win = window,
opt = {
clamp: options.clamp || 2,
useNativeClamp: typeof(options.useNativeClamp) != 'undefined' ? options.useNativeClamp : true,
splitOnChars: options.splitOnChars || ['.', '-', '–', '—', ' '], //Split on sentences (periods), hypens, en-dashes, em-dashes, and words (spaces).
animate: options.animate || false,
truncationChar: options.truncationChar || '…',
truncationHTML: options.truncationHTML
},
sty = element.style,
originalText = element.innerHTML,
supportsNativeClamp = typeof(element.style.webkitLineClamp) != 'undefined',
clampValue = opt.clamp,
isCSSValue = clampValue.indexOf && (clampValue.indexOf('px') > -1 || clampValue.indexOf('em') > -1),
truncationHTMLContainer;
if (opt.truncationHTML) {
truncationHTMLContainer = document.createElement('span');
truncationHTMLContainer.innerHTML = opt.truncationHTML;
}
// UTILITY FUNCTIONS __________________________________________________________
/**
* Return the current style for an element.
* @param {HTMLElement} elem The element to compute.
* @param {string} prop The style property.
* @returns {number}
*/
function computeStyle(elem, prop) {
if (!win.getComputedStyle) {
win.getComputedStyle = function(el, pseudo) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle && el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return this;
}
}
return win.getComputedStyle(elem, null).getPropertyValue(prop);
}
/**
* Returns the maximum number of lines of text that should be rendered based
* on the current height of the element and the line-height of the text.
*/
function getMaxLines(height) {
var availHeight = height || element.clientHeight,
lineHeight = getLineHeight(element);
return Math.max(Math.floor(availHeight/lineHeight), 0);
}
/**
* Returns the maximum height a given element should have based on the line-
* height of the text and the given clamp value.
*/
function getMaxHeight(clmp) {
var lineHeight = getLineHeight(element);
return lineHeight * clmp;
}
/**
* Returns the line-height of an element as an integer.
*/
function getLineHeight(elem) {
var lh = computeStyle(elem, 'line-height');
if (lh == 'normal') {
// Normal line heights vary from browser to browser. The spec recommends
// a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff.
lh = parseInt(computeStyle(elem, 'font-size')) * 1.2;
}
return parseInt(lh);
}
// MEAT AND POTATOES (MMMM, POTATOES...) ______________________________________
var splitOnChars = opt.splitOnChars.slice(0),
splitChar = splitOnChars[0],
chunks,
lastChunk;
/**
* Gets an element's last child. That may be another node or a node's contents.
*/
function getLastChild(elem) {
//Current element has children, need to go deeper and get last child as a text node
if (elem.lastChild.children && elem.lastChild.children.length > 0) {
return getLastChild(Array.prototype.slice.call(elem.children).pop());
}
//This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying
else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue == '' || elem.lastChild.nodeValue == opt.truncationChar) {
elem.lastChild.parentNode.removeChild(elem.lastChild);
return getLastChild(element);
}
//This is the last child we want, return it
else {
return elem.lastChild;
}
}
/**
* Removes one character at a time from the text until its width or
* height is beneath the passed-in max param.
*/
function truncate(target, maxHeight) {
if (!maxHeight) {return;}
/**
* Resets global variables.
*/
function reset() {
splitOnChars = opt.splitOnChars.slice(0);
splitChar = splitOnChars[0];
chunks = null;
lastChunk = null;
}
var nodeValue = target.nodeValue.replace(opt.truncationChar, '');
//Grab the next chunks
if (!chunks) {
//If there are more characters to try, grab the next one
if (splitOnChars.length > 0) {
splitChar = splitOnChars.shift();
}
//No characters to chunk by. Go character-by-character
else {
splitChar = '';
}
chunks = nodeValue.split(splitChar);
}
//If there are chunks left to remove, remove the last one and see if
// the nodeValue fits.
if (chunks.length > 1) {
// console.log('chunks', chunks);
lastChunk = chunks.pop();
// console.log('lastChunk', lastChunk);
applyEllipsis(target, chunks.join(splitChar));
}
//No more chunks can be removed using this character
else {
chunks = null;
}
//Insert the custom HTML before the truncation character
if (truncationHTMLContainer) {
target.nodeValue = target.nodeValue.replace(opt.truncationChar, '');
element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar;
}
//Search produced valid chunks
if (chunks) {
//It fits
if (element.clientHeight <= maxHeight) {
//There's still more characters to try splitting on, not quite done yet
if (splitOnChars.length >= 0 && splitChar != '') {
applyEllipsis(target, chunks.join(splitChar) + splitChar + lastChunk);
chunks = null;
}
//Finished!
else {
return element.innerHTML;
}
}
}
//No valid chunks produced
else {
//No valid chunks even when splitting by letter, time to move
//on to the next node
if (splitChar == '') {
applyEllipsis(target, '');
target = getLastChild(element);
reset();
}
}
//If you get here it means still too big, let's keep truncating
if (opt.animate) {
setTimeout(function() {
truncate(target, maxHeight);
}, opt.animate === true ? 10 : opt.animate);
}
else {
return truncate(target, maxHeight);
}
}
function applyEllipsis(elem, str) {
elem.nodeValue = str + opt.truncationChar;
}
// CONSTRUCTOR ________________________________________________________________
if (clampValue == 'auto') {
clampValue = getMaxLines();
}
else if (isCSSValue) {
clampValue = getMaxLines(parseInt(clampValue));
}
var clampedText;
if (supportsNativeClamp && opt.useNativeClamp) {
sty.overflow = 'hidden';
sty.textOverflow = 'ellipsis';
sty.webkitBoxOrient = 'vertical';
sty.display = '-webkit-box';
sty.webkitLineClamp = clampValue;
if (isCSSValue) {
sty.height = opt.clamp + 'px';
}
}
else {
var height = getMaxHeight(clampValue);
if (height <= element.clientHeight) {
clampedText = truncate(getLastChild(element), height);
}
}
return {
'original': originalText,
'clamped': clampedText
}
}
window.$clamp = clamp;
})();
$(document).ready(function(){
$clamp(clamp1, {clamp: 1});
$clamp(clamp2, {clamp: 3});
$clamp(clamp3, {clamp: '100px'});
});
Cras vel ligula a elit pretium convallis. Nunc ac nisl nisi. Vestibulum ut ullamcorper nibh. Phasellus dictum nisi quis ullamcorper finibus. Phasellus fringilla purus ut augue varius vulputate. Nullam nec nisl dignissim, varius sem pretium, commodo orci. Cras tortor nisl, pharetra sodales lobortis a, vestibulum ut libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Pellentesque rutrum urna elit, sed cursus felis placerat efficitur. Curabitur tempor velit magna, mollis malesuada risus lacinia sed. Mauris tristique id mi et cursus. Quisque consectetur velit in lacus euismod scelerisque. Vestibulum ac malesuada libero, eget auctor turpis. Integer pellentesque a ipsum non faucibus. Quisque ultricies sapien ut tellus bibendum aliquam.
Cras vel ligula a elit pretium convallis. Nunc ac nisl nisi. Vestibulum ut ullamcorper nibh. Phasellus dictum nisi quis ullamcorper finibus. Phasellus fringilla purus ut augue varius vulputate. Nullam nec nisl dignissim, varius sem pretium, commodo orci. Cras tortor nisl, pharetra sodales lobortis a, vestibulum ut libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Pellentesque rutrum urna elit, sed cursus felis placerat efficitur. Curabitur tempor velit magna, mollis malesuada risus lacinia sed. Mauris tristique id mi et cursus. Quisque consectetur velit in lacus euismod scelerisque. Vestibulum ac malesuada libero, eget auctor turpis. Integer pellentesque a ipsum non faucibus. Quisque ultricies sapien ut tellus bibendum aliquam.
Cras vel ligula a elit pretium convallis. Nunc ac nisl nisi. Vestibulum ut ullamcorper nibh. Phasellus dictum nisi quis ullamcorper finibus. Phasellus fringilla purus ut augue varius vulputate. Nullam nec nisl dignissim, varius sem pretium, commodo orci. Cras tortor nisl, pharetra sodales lobortis a, vestibulum ut libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Pellentesque rutrum urna elit, sed cursus felis placerat efficitur. Curabitur tempor velit magna, mollis malesuada risus lacinia sed. Mauris tristique id mi et cursus. Quisque consectetur velit in lacus euismod scelerisque. Vestibulum ac malesuada libero, eget auctor turpis. Integer pellentesque a ipsum non faucibus. Quisque ultricies sapien ut tellus bibendum aliquam.
View Statistics
This Week
692
This Month
2173
This Year
4142
Add Comment
Other Items in javascript
get current year in javascript
find a text string and replace it in javascript
check if an item id exists in javascript
Twitter Post Fetcher v18.0.4 - javascript twitter feed fetcher
Are you sure you want to navigate away from this page? #JavaScript warning
floating message box on bottom right of screen with close button
share to twitter javascript button function open a new window
share to linked in current url button with javascript
Get current URL and add a share to facebook share button with it
encode url with javascript
Twitter Post Fetcher Script
Javascript Objects Notes
javascript add class to element
update value of element using javascript
javascript attach a click event to an id not using jquery
console dir usage
how to write a javascript string over multiple lines
best way to write html into an existing page javascript
Uncaught TypeError: Cannot set properties of null (setting 'onclick')
check url hash using javascript
submit form with javascript
Converting PHP to Javascript for State Extraction by numeric value Australian State Names
get the value from a textarea element
javascript get content from element
convert characters to entities using javascript replace
Auto Create HTML Code Snippets
loop to arr.length or array length
get tomorrows date with javascript
get yesterdays date with javascript
add new random image with button
Create Strings using Template Literals
Darkmode JS - Add darkmode to your site with one script
Use destructuring assignment within the argument to the function half to send only max and min inside the function.
Using Destructuring and the Rest Parameter to Reassign Array Elements
Use destructuring assignment to swap the values of a and b
Sweet Alert 2 Methods and Examples
How to Assign the Value of One Variable to Another in Javascript
Slick Slider Carousel with Custom Next and Prev Buttons
Console Tips and Tricks
javascript random string to put on url for cache
javascript try catch example function
load json data url or api with javascript
log the console log output to a div
javascript basic test array and loop
how to join an array in javascript using the join method
show the current date in javascript
get element by id and hide it
get element by id with javascript
set a cookie on click and then check if the cookie is set and dont show that message again
console table rather than console log for javascript objects and arrays
Related Search Terms
Other Categories in Code
alpine js apps c css factorio font awesome images linux quick modals sqlite site bugs site updates slick slider sliders testing windows apps apache api apps asp bat bootstrap bootstrap templates charts cookies core css css filters css grid design elements docker domains emoji fancybox fonts foundation framework gimp git html icons ideas image formatting images javascript javascript functions jquery js linux mac misc modals mysql nginx node php php errors php function php functions php simple html dom pi400 python react regex sections simple_html_dom simplepie php site bugs site documentation slick slider sql sqlite ssh sublime svg svg css templates tools virtual box vscode vue webdev windows windows 11 windows commands wordpress