public
Created

  • Download Gist
trimText.js
JavaScript
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
function getHeight(elementStyle) {
return parseInt(elementStyle.height) + parseInt(elementStyle["margin-top"]) + parseInt(elementStyle["margin-bottom"]);
}
 
function trimText(element, elementHeight, maxHeight) {
var tmpText = element.innerHTML;
var words = tmpText.split(" ");
var min = 0;
var max = words.length;
var mid = Math.ceil((max + min) / 2);
do {
mid = Math.ceil((max + min) / 2);
element.innerHTML = words.slice(0, mid).join(" ");
elementHeight = getHeight(window.getComputedStyle(element));
if (elementHeight > maxHeight) {
max = mid;
} else {
min = mid - 1;
}
} while((mid - min) > 1 || (max - mid) > 1)
 
if (elementHeight > maxHeight) {
element.innerHTML = "";
elementHeight = getHeight(window.getComputedStyle(element));
}
 
return elementHeight;
}
 
function trimArticles(articlesSelector) {
var articles = document.querySelectorAll(articlesSelector);
var article;
 
for (var i = 0; i< articles.length; i++) {
article = articles[i];
var articleStyle = window.getComputedStyle(article);
var maxHeight = parseInt(articleStyle.height) - parseInt(articleStyle["padding-top"]) - parseInt(articleStyle["padding-bottom"]);
 
var element, elementStyle, elementHeight;
for (var j = 0; j < article.children.length; j++) {
element = article.children[j];
elementStyle = window.getComputedStyle(element);
if (elementStyle["float"] != "none") {
continue;
}
elementHeight = getHeight(elementStyle);
if (maxHeight > 0) {
if (elementHeight > maxHeight) {
elementHeight = trimText(element, elementHeight, maxHeight);
}
} else {
element.innerHTML = "";
elementHeight = getHeight(window.getComputedStyle(element));
}
maxHeight = maxHeight - elementHeight;
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.