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.

1
  • 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. Commented Nov 1, 2015 at 11:53

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.