2

You know what I mean? Like let's say we have:

<div style="width:100px;font-size:10px">Some Text</div>

But then we could also possibly have a much longer text string in that div, in that case I would want that div to have font-size:7px or whatever, so that the whole string fits without overflowing.

I'm sure there's already something like this written, I wouldn't want to reinvent this. Preferably a jQuery plugin?

Any suggestions would be appreciated! Thanks

adamJLev
  • 13,713
  • 11
  • 60
  • 65
  • This might help: http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – Nosredna Jul 24 '09 at 16:11
  • This question is very similar to a one [asked earlier today](http://stackoverflow.com/questions/1177320/programmatically-determine-font-size-for-single-line-display/1177753#1177753). – Nick Riggs Jul 24 '09 at 16:13

1 Answers1

5

Based on an answer proposed in Nick's question:

$(function() {
    $(".shrinkByWidth").each(function() {
        var targetWidth = $(this).parent(':first').width();

        if (isNaN(parseInt($(this).css("font-size"))))
            $(this).css("font-size", '24px');

        while ($(this).width() > targetWidth) 
        {
            $(this).css("font-size", (parseInt($(this).css("font-size")) - 1) + 'px');
        }
    });
});

Works great for me!

adamJLev
  • 13,713
  • 11
  • 60
  • 65