3

Is there a js or jQuery function that will detect if the innerHTML or text is within a certain # of pixels from being clipped by its container?

I will need to do this for a few hundred elements on a page, so performance is a bit important.

Example - determine if the text in this <td> is within 5px of exceeding its width:

<td class="cell">
  12,3423
</td>

.cell {
   width: 20px;
}
Don P
  • 60,113
  • 114
  • 300
  • 432

2 Answers2

4

Try this

$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>';
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};

$(function(){
   alert($('.cell').textWidth());    
});

Fiddle http://jsfiddle.net/Hpyay/

It can be possible duplicate (and above code copied from) of Calculating text width

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

you need to wrap in something (p, div whatever) then you get that element width/height

 <td><p>text...</p></td>

make your calculation from $("td>p").width()

but if it's text only or image (with a max-width:100%) unless you no-wrap...

mikakun
  • 2,203
  • 2
  • 16
  • 24