User9123
User9123

Reputation: 23

Find position of text overflow using Javascript

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.

Upvotes: 2

Views: 536

Answers (1)

user663031
user663031

Reputation:

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");

Upvotes: 2

Related Questions