Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to measure maximal word wrap width in left-aligned text?

Is it possible to measure actual word wrap width in left-aligned text?

For example, saying below is aligned left. Depending on element width, it can be wrapped at word "their" or at word "the".

The width, marked red, does not coincide with element width, since wrapping occurs at random place when word does not fit the line.

enter image description here

Is it possible to measure this width?

like image 966
Dims Avatar asked Nov 01 '25 15:11

Dims


1 Answers

You can query the text width (and more) when you create a Range from the text node and read its dimensions with getBoundingClientRect().

function getTextRect( containerNode ) {
  // For simplicity, we assume plain text here
  // (no nested markup)
  var textRect,
      textNode = containerNode.childNodes[0],
      textRange = document.createRange();

  textRange.selectNode( textNode );
  textRect = textRange.getBoundingClientRect();

  // Clean up
  textRange.detach();

  return textRect;
}

// You can read the width with getTextRect( someNode ).width

You can see it in action in this JSBin demo.

This method is well supported in IE9+ (doesn't work in IE8); Chrome, FF, Opera already support it for ages. MDN doesn't have compatibility information for Safari, though. So I have briefly checked the demo in iOS8, iOS9, and with Safari 9 on the desktop – works like a charm.

like image 84
hashchange Avatar answered Nov 03 '25 06:11

hashchange