2

Similar to Determine if an HTML element's content overflows, how can you find the index position of the element that overflows?

Example: If we have a long string inside a div that overflows at the 100th character, how can I find that position?

Edit: More detail because @dfsq asked: I'm trying to create a nice plain text reader, with page flipping.

Community
  • 1
  • 1
User9123
  • 23
  • 3
  • You can find it, yes. Might be verbose, but possible. The real question is why you need it, because probably there is better and simpler way to solve your task. – dfsq Nov 01 '15 at 11:53

1 Answers1

2

Here is some sample code. You will need to start off with zero characters, then add each character in one by one and detect when the offsetWidth exceeds the scrollWidth.

function find_overflow_index(elt, str) {
  elt.textContent = '';

  for (var i=0; i < str.length; i++) {
    elt.textContent += str[i];
    if (elt.scrollWidth < elt.offsetWidth) return i;
  }

  return -1;  // no overflow
}

find_overflow_index(
  document.getElementById("foo"), 
  "Long string which might overflow");
  • Clever answer, but would it not be better to split on spaces and loop through the resulting array adding words? Fewer iterations, fewer DOM manipulations, and wouldn't page-flip in the middle of a word. Might also want to mention that this should be added to the browser's resize event also so the pagination gets recalculated when the user resizes. – Jared Smith Nov 01 '15 at 19:52