0

I need my plugin to detect element's line-breaks, here is the code:

$.fn.inlineOffset = function (){
    if ($(this).css('text-indent') == '0px' && $(this).height() != 17) {
      var el = $('<i/>').css('display', 'inline').insertBefore(this[0]);
          pos = el.offset();
      el.remove();
      return pos;
    }
    else {
      var pos = $(this).offset()
      return pos;
    }
  };

As you can see, it would only work if element's height is 17px. But what if I need to set different height? I need this solution, because if I try to add element before first letter in new line it appears at top left corner of it's parrent and I only need to add when the line of text is broken.

Nephie
  • 67
  • 3
  • 10
  • 1
    see here: http://stackoverflow.com/questions/4671713/detecting-line-breaks-with-jquery – sjkm Nov 03 '13 at 22:31
  • I saw it, but it says that it doesnt work in some situations, for example when item is floating – Nephie Nov 03 '13 at 22:33
  • what I would do is create a text element, set the width, font-size etc. to the same as the original element you want to test and get it's height when white-space is nowrap and get it's height when white-space is normal. if those two values aren't the same then you know that there is more than one line. That's quite simple (lightweight) and works in most scenarios. – sjkm Nov 03 '13 at 22:37
  • See below. I worked out a solution. – sjkm Nov 04 '13 at 10:49

2 Answers2

0

One method I've used is wrap every word in a span by splitting text into array at space and joining aray with span tags, loop through all the spans to check position. WHen top increases you found a line break

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

I worked out a solution on the fly. Give it a try here: http://jsfiddle.net/6V2Pd/1/ The key point are the following lines of code:

//here we get the calculated height of the text element when white space is nowrap (single line)
$target.css('white-space', 'nowrap');
var nowrapHeight = $target.height();

//here we get the calc. height when white space is normal (breaks are allowed)
$target.css('white-space', 'normal');
var normalwrapHeight = $target.height();

// here we are going to compare the two values and come to a conclusion
// if nowrapHeight != normalwrapHeight => it's a multiline text
...
sjkm
  • 3,887
  • 2
  • 25
  • 43