Created
December 11, 2016 17:41
-
-
Save paulera/477d27d9cb6c896db5f863d513440f64 to your computer and use it in GitHub Desktop.
Reduce a text font-size until div fits maximum height defined in pixels.
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
/** | |
* Decrease font-size to limit div's height. | |
* Requires jQuery and must be called with setTimeout (as below) | |
* to wait for elements to be rendered before sdjust them. | |
* | |
* Example: | |
* <div data-auto-max-height="50">The font-size of this text will decrease until the div has 50px in height</div> | |
*/ | |
$(document).ready(function() { | |
'use strict'; | |
// Decrease font-size of DOM Elements with the data-auto-max-height | |
// attribute defined to a max height in pixels | |
setTimeout(function() { | |
$.each ($('[data-auto-max-height]'), function (index, value) { | |
// element to scale down | |
var scaleme = $(value); | |
// auto-max-height must be a positive integer | |
var maxheight = scaleme.data('auto-max-height'); | |
if (!parseInt(maxheight) > 0) { | |
return; | |
} | |
// get element height | |
var height = scaleme.height(); | |
// if bigger than maxheight, runs a font resizing. | |
// Goo result with less interactions | |
if (height > maxheight) { | |
var adjust = null; // variable used to increment(+)/decrement(-) font size | |
var i = 0; | |
// variable used to handle the font-size in the loops | |
var fontsize = parseFloat(scaleme.css('font-size')); | |
// decrease font size in px by parseInt(height / maxheight) until | |
// is smaller than maxheight | |
while( height > maxheight ) { | |
adjust = -1 * parseInt(height / maxheight); | |
fontsize = fontsize + adjust; | |
height = scaleme.css('font-size', fontsize + 'px' ).height(); | |
// debug: console.log (i+"\t"+height+"\t"+adjust); | |
if (i > 100) return; // loop protection | |
} | |
// increase font size by 0.5px until pass maxheight again | |
adjust = + 0.5; | |
while( height < maxheight ) { | |
fontsize = fontsize + adjust; | |
height = scaleme.css('font-size', fontsize + 'px' ).height(); | |
// debug: console.log (i+"\t"+height+"\t"+adjust); | |
if (i > 100) return; // loop protection | |
} | |
// decrease font size by 0.5px until is smaller than maxheight | |
adjust = - 0.1; | |
while( height > maxheight ) { | |
fontsize = fontsize + adjust; | |
height = scaleme.css('font-size', fontsize + 'px' ).height(); | |
// debug: console.log (i+"\t"+height+"\t"+adjust); | |
if (i > 100) return; // loop protection | |
} | |
// debug: console.log ("Final = "+scaleme.height()); | |
} | |
}); | |
}, 1000); // milisseconds to wait after loading the page, for then resize the fonts. | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment