Skip to content

Instantly share code, notes, and snippets.

@TannerRogalsky
Created May 4, 2012 21:00
Show Gist options
  • Save TannerRogalsky/2597704 to your computer and use it in GitHub Desktop.
Save TannerRogalsky/2597704 to your computer and use it in GitHub Desktop.
autoSizeText.js
(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