SoulieBaby
SoulieBaby

Reputation: 5471

Enlarge / shrink text to dynamically fill a div using jquery?

I've seen a few similar posts and have tried out the answers given, but I can't seem to get this to work (for me anyway).

Basically I'm looking for something that will automatically resize (enlarge or shrink) my text to fit a set width div over multiple lines. Where line 1 is the largest, line 2 smaller and line 3 smallest text sizes and (hopefully) justifying the text as it goes along.. If that makes any sense at all?

Any help would be appreciated! :)

EDIT: I forgot to mention it will only run over 2-3 lines at the most with a set div width of 286px.

I've tried the following codes:

;(function($) {
$.fn.textfill = function(options) {
    var fontSize = options.maxFontPixels;
    var ourText = $('span:visible:first', this);
    var maxHeight = $(this).height();
    var maxWidth = $(this).width();
    var textHeight;
    var textWidth;
    do {
        ourText.css('font-size', fontSize);
        textHeight = ourText.height();
        textWidth = ourText.width();
        fontSize = fontSize - 1;
    } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
    return this;
}
})(jQuery);
$(document).ready(function(e){
  $('.testimonial').textfill({ maxFontPixels: 36 });
});

Auto-size dynamic text to fill fixed size container

$( '.testimonial' ).each(function ( i, box ) {
    var width = $( box ).width(),
        html = '<span style="white-space:nowrap"></span>',
        line = $( box ).wrapInner( html ).children()[ 0 ],
        n = 100;
    $( box ).css( 'font-size', n );
    while ( $( line ).width() > width ) {
        $( box ).css( 'font-size', --n );
    }
    $( box ).text( $( line ).text() );
  });

JavaScript Scale Text to Fit in Fixed Div

Upvotes: 0

Views: 3054

Answers (1)

Control Freak
Control Freak

Reputation: 13233

You would need to code this yourself based on your description, something like this should work:

  1. Get the size of the div using .innerWidth() and .innerHeight()
  2. Based on your own mathematical formula, you would set a tolerance on how big you want the font size to be depending on the size of the wrapping div. Toggle the font size using $.css('font-size','12px'); , etc.

So you would do it like this:

 // get the size of the div
 var w = $('div').innerWidth();
 var h = $('div').innerHeight();

 // your own formula to your liking
 if (w >= 100) { fontsize = 11 }
 elseif (w >= 200) { fontsize = 12 }
 else { fontsize = 10 }

 //text to resize
 $('div span').css('font-size', fontsize + 'px');

Or maybe there is a plugin for it, try google.

Upvotes: 2

Related Questions