mac elipses

by Maxim Mazurok

HTML

<div id="div" style="overflow: hidden; width: 200px; white-space: nowrap;">
  <span id="span" style="display: inline-block">this is a quite long text that has some words and I want it to be split in half</span>
</div>

JavaScript

const span = document.getElementById("span");
const div = document.getElementById("div");
const originalText = span.textContent;
const textLength = originalText.length;
let part1 = originalText.substr(0, Math.floor(textLength/2));
let part2 = originalText.substr(Math.floor(textLength/2));
let trimPart1 = true;
while (span.clientWidth > div.clientWidth) {
	if (trimPart1) {
  	part1 = part1.substr(0, part1.length - 1);
  } else {
  	part2 = part2.substr(-1 * (part2.length - 1));
  }
	span.textContent = part1 + "..." + part2;
  trimPart1 = !trimPart1;
}