JS: check if text exceeds container width

Is there a js or jQuery function that will determine if innerHTML or text will be within a certain number of pixels of its container?

I will need to do this for several hundred elements on the page, so performance is a bit of a concern.

Example. Determine if the text in this <td>

is within 5 pixels above its width:

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

.cell {
   width: 20px;
}

      

+3


source to share


2 answers


try it

$.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 may be possible to duplicate ( and above code copied from ) Calculating text width

+4


source


you need to wrap something (p, div any) then you will get this element width / height

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

      



do your calculation with $("td>p").width()

but if it is just text or image (s max-width:100%

) if you don't bypass ...

0


source







All Articles