Created
May 31, 2011 03:43
-
-
Save meirish/999827 to your computer and use it in GitHub Desktop.
jquery take on this: https://gist.github.com/428898/e882078f10a06e55fa905a89a6ae65f30331746a
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var setTextMeasure = function (contentElement, targetMeasure, maxSize, minSize) { | |
if (!contentElement) contentElement = $(document.createElement('p')); | |
if (!targetMeasure) targetMeasure = 66; | |
if (!maxSize) maxSize = 16; | |
if (!minSize) minSize = 9; | |
var body = $('body'); | |
var sizer = contentElement.clone(); | |
sizer.css({'margin': 0, 'padding': 0, 'color': 'transparent', 'backgroundColor': 'transparent', 'position': 'absolute'}); | |
var letters = 'aaaaaaaabbcccddddeeeeeeeeeeeeeffgghhhhhhiiiiiiijkllllmmnnnnnnnooooooooppqrrrrrrsssssstttttttttuuuvwxyyz'; | |
sizer.text(letters); | |
body.append(sizer); | |
var characterWidth = sizer.width() / letters.length; | |
sizer.remove(); | |
var contentWidth = contentElement.width(); | |
var measuredFontSize = parseFloat( body.css('font-size').replace('px', '') ); | |
var actualMeasure = contentWidth / characterWidth; | |
var newMeasure = measuredFontSize * actualMeasure / targetMeasure; | |
if (newMeasure > maxSize) newMeasure = maxSize; | |
if (newMeasure < minSize) newMeasure = minSize; | |
body.css('font-size', newMeasure + "px"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment