views:

47

answers:

2
<div style="width: 100px; height:50px; line-height:50px; overflow:hidden;">
    <p>A short line</p>
</div>

<div style="width: 100px; height:50px; line-height:50px; overflow:hidden;">
    <p>A really really really long line</p>
</div>

Wrapped text in the second example gets cut off because of the line-height:50px which should be 25px in this case. How do I use jQuery to find if theres single or multi-line text in an element?

Thanks!

A: 

Multi-line text occurs when the width of the text is greater than the width of the document

In a previous SO question, I found this solution to discovering text width. Now all you need to do is compare the text width to the width of the div (in this case to 100px). If it's greater, it's going to be multiline. Remeber to include any padding may add later to your DIV.

Just for help, here's the code I'm referring to (though it's not mine)

$.fn.textWidth = function(){
  var sensor = $('<div />').css({margin: 0, padding: 0});
  $(this).append(sensor);
  var width = sensor.width();
  sensor.remove();
  return width;
};

Hope it helps!

Gausie
A: 

Perhaps you could set the height of the div to auto, grab its height and store it in a variable, set its height back to 50px, then check the variable to see if the height of the element was over 50px. If it was, then you can run a function to adjust the line height accordingly. You could just take the variable and divide it by 50 to get an approximate number of lines (i.e. if height = 150px, you can assume that there are 3 lines of text) then you can set the line height accordingly.

Not sure if this will work, but something like this if you're using jQuery:

$('div').css('height', 'auto');

var divHeight = $('div').height();

$('div').css('height', '50px');

if (divHeight > 50) {
    var lineHeight = (divHeight / 50) + 'px';

    $('div').css('line-height', 'lineHeight');
}
Chris Schmitz