Line clamp demo

clamp text to exactly n lines

by evan

HTML

<div id="label">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

<div id="output">
</div>
</div>

CSS

#label {
  font-family: "Open Sans", sans-serif;
  font-size: 12px;
  line-height: 16px;

  width: 180px;
  padding: 0 6px;
}

#output {
  background: lightgray;
  color: #111111;
  position: fixed;
  top: 0px;
  right: 0px;
  padding: 4px;
  font-size: 14px;
  font-family: "Monaco", monospace;
  width: 280px;
  min-height: 30px;
}

JavaScript

function log(text) {
  const output = document.getElementById('output');
  const p = document.createElement('p');
  p.innerText = text;
  output.appendChild(p);
}

const label = document.getElementById('label');
const labelText = label.firstChild;
const labelTextValue = labelText.wholeText.trim();

const range = document.createRange();
range.setStart(labelText, 0);
range.setEnd(labelText, 0);

let index = 0;
let spaceIndex = [];
let textHeight = 0;
let heightChanges = 0;
let lastIndex = 0;
while (index < labelTextValue.length) {
  let found = labelTextValue.indexOf(' ', index + 1);
  if (found > 0) {
    range.setEnd(labelText, found);
    const {
      height
    } = range.getBoundingClientRect();
    if (height !== textHeight) {
      textHeight = height;
      heightChanges++;
    }

    /*     log([found, index, lastIndex, heightChanges, labelTextValue.substr(0, lastIndex)]);
     */
    if (heightChanges > 2) {
      log(labelTextValue.substr(0, lastIndex));
      break;
    }

  } else {
    break;
  }

  lastIndex = index;
  index = found;

}
log(spaceIndex)

/* let height = 0;
let heightChanges = 0;
let spaceIndex = labelTextValue.indexOf(' ');
while (spaceIndex > 0) {
  
} */