Skip to content

Instantly share code, notes, and snippets.

@philippze
Created July 2, 2014 12:48
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 philippze/bd46ebb616d1de531cf8 to your computer and use it in GitHub Desktop.
Save philippze/bd46ebb616d1de531cf8 to your computer and use it in GitHub Desktop.
Shorten a text until it's below a certain heigt.
(function ($) {
/**
* Shorten a text until it's below a certain heigt.
* Pass the parameter 'height' in px with the options.
*
* Usage:
*
* $('.teasers').truncateTeasers({height: 40});
*
* This removes words from the end of the text in all .teasers
* until it is lower than 40px.
*
* WARNING: This script will be inefficient if you have very long
* captions everywhere.
*
**/
'use strict';
var element_too_high = function ($element, max_height) {
return $element.height() > max_height;
},
stripDots = function (text) {
var splitIndex = text.length - 4,
lastCharacters = text.substr(splitIndex);
if (lastCharacters === ' ...') {
text = text.substr(0, splitIndex);
}
return text;
},
removeLastWord = function ($element) {
var text = stripDots($element.text()),
lastIndex = text.lastIndexOf(" "),
shorter_text = text.substring(0, lastIndex);
$element.text(shorter_text + ' ...');
};
jQuery.fn.truncateTeasers = function (options) {
return this.each(function () {
while (element_too_high($(this), options.height)) {
removeLastWord($(this));
}
});
};
}(jQuery));
@mayureshgoyal
Copy link

This worked like a charm. The perfect line clamping solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment