Here is my solution: I measure the text in a new div in the provided div, so the style should be inherited. Then I insert the text into the div at intervals to set the font size. It will be maximized to the default font size, but will decrease.
It does not loop: it only draws the text once in the throwing meta before drawing directly into the provided div. See @Hoffmann's answer - I just didn't like the whole “plugin” to answer the question.
jquery required.
var txt = txt || {} txt.pad_factor = 1.1; txt.insertText_shrinkToFit = function(div,text) { var d = txt.cache || $('<div></div>'); txt.cache = d; d.css('white-space','nowrap'); d.css('position','absolute'); d.css('top','-10000px'); d.css('font-size','1000px'); var p = $(div); var max_w = parseInt(p.css('max-width')) || p.width(); var max_h = parseInt(p.css('font-size')); p.append(d); d.html(text); var w = d.width() * txt.pad_factor; d.remove(); var h = Math.floor(max_w*1000/w); var s = ( max_h < h ? max_h : h ) + "px"; p.html('<SPAN style="font-size:' + s + '">' + text + '</SPAN>'); }
For example:
<html><head><script src=http://code.jquery.com/jquery-latest.min.js></script> <script></script></head><body> <div id=mysmalldiv style="max-width:300px;font-size:50px"></div> <script> txt.insertText_shrinkToFit("#mysmalldiv","My super long text for this div."); </script> </body></html>
For testing: so I found that I need 1.1 pad_factor; which you can customize to your needs.
<div id=mytestdiv style="max-width:300px;font-size:50px"></div> <script> var t = "my text "; var i = 0; var f = function() { t += i + " "; txt.insertText_shrinkToFit("#mytestdiv",t); i++; if(i < 100) setTimeout(f,1000); } f(); </script>
Note: It is assumed that the font size is px. I have not tested with em or pt.
JJ Stiff Sep 29 '14 at 4:25 2014-09-29 04:25
source share