textfit.js
author Andrew Gwozdziewycz <hg@apgwoz.com>
Fri Sep 07 21:33:34 2007 -0700 (4 years ago)
changeset 0 5cfc9923488e
permissions -rw-r--r--
* initial import
     1 /**
     2  * (C) 2007 Andrew Gwozdziewycz <apgwoz@gmail.com>
     3  * VERSION: 0.1, Released under an MIT License. 
     4  * URL: http://www.apgwoz.com/textfit/
     5  **/
     6 function textFit(node, minfs, maxfs, width, height) {
     7     var fits = function(sz) {
     8         node.style.fontSize = sz + 'px';
     9         return node.offsetWidth <= width && node.offsetHeight <= height;
    10     };
    11     var hfs = maxfs - minfs;
    12     var tst = minfs + Math.ceil(hfs / 2);
    13     var opsz = node.style.fontSize;
    14     
    15     while ((hfs/2) >= 1) {
    16         if (fits(tst)) {
    17             minfs = tst;
    18         }
    19         else {
    20             maxfs = tst;
    21         }
    22         hfs = maxfs - minfs;
    23         tst = minfs + Math.ceil(hfs/2);
    24     }
    25     opsz = fits(maxfs) ? maxfs: minfs;
    26     node.style.fontSize = opsz + 'px';
    27 }