Created
May 4, 2012 21:00
-
-
Save TannerRogalsky/2597704 to your computer and use it in GitHub Desktop.
autoSizeText.js
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
(function ($) { | |
$.fn.getTextWidth = function() { | |
var spanText = $("BODY #spanCalculateTextWidth"); | |
if (spanText.size() <= 0) { | |
spanText = $("<span id='spanCalculateTextWidth" + U_gen_id() + "' style='filter: alpha(0);'></span>"); | |
spanText.appendTo("BODY"); | |
} | |
var valu = this.val(); | |
if (!valu) valu = this.text(); | |
spanText.text(valu); | |
spanText.css({ | |
"fontSize": this.css('fontSize'), | |
"fontWeight": this.css('fontWeight'), | |
"fontFamily": this.css('fontFamily'), | |
"position": "absolute", | |
"top": 0, | |
"opacity": 0, | |
"left": -2000 | |
}); | |
var width = spanText.outerWidth() + parseInt(this.css('paddingLeft')); | |
spanText.remove(); | |
return width; | |
}; | |
$.fn.autoSizeText = function(){ | |
var newFontSize = 0; | |
while(this.getTextWidth() > this.width()){ | |
var fontSize = this.css("font-size"); | |
newFontSize = --fontSize.match(/[\d\.]+/g)[0]; | |
this.css("font-size", newFontSize + "px"); | |
} | |
return this; | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment