Skip to content

Instantly share code, notes, and snippets.

@dylanjha
Forked from kenkeiter/text_extents.js
Last active August 7, 2018 09:26
Show Gist options
  • Save dylanjha/5608911 to your computer and use it in GitHub Desktop.
Save dylanjha/5608911 to your computer and use it in GitHub Desktop.
// an element with class 'font_resize' with css properties:
// * max-height
// * max-width
// * font-size
// the element has children span elements, the font size inside these spans will re resized.
;(function($){
$.fn.fontResize = function(options){
var spans = $('span:visible', this);
var heightMax = parseInt($(this).css('max-height'), 10),
widthMax = parseInt($(this).css('max-width'), 10),
fontSize = parseInt($(this).css('font-size'), 10); /* max font size */
do{
var textHeight = 0,
textWidth = 0;
$(spans).each(function(){
$(this).css('font-size', fontSize);
if($(this).height() > textHeight){ textHeight = $(this).height(); }
textWidth = textWidth + $(this).width();
});
fontSize = fontSize - 1;
} while ((textHeight > heightMax || textWidth > widthMax) && fontSize > 3);
return this;
};
})(jQuery);
$(document).ready(function(){
$('.font-resize').fontResize();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment