Skip to content

Instantly share code, notes, and snippets.

@cherring
Forked from jobwat/helper.js
Created June 7, 2011 00:14
Show Gist options
  • Save cherring/1011411 to your computer and use it in GitHub Desktop.
Save cherring/1011411 to your computer and use it in GitHub Desktop.
Resize text font-size to fit in parent element width
Helpers.updateResizeInput = function(el, text){
if(el.localName == "input" || el[0].localName == "input"){ // inputs are a pain
el.parent().prepend('<span id="test" />');
var theSpan = $('span#test', el.parent());
theSpan.value = text;
Helpers.updateResizeInput(theSpan, text);
el.css('font-size', theSpan.css('font-size'));
el.css('margin-top', theSpan.css('margin-top'));
el[0].value = text;
theSpan.remove();
}
else{
el.html(text);
var parentWidth = el.parent().width();
var parentHeight = el.parent().height();
var fontSize = 24; // max, biggest value
el.css('width', 'auto');
el.css('font-size', fontSize+'px');
el.css('margin-top', '6px');
while(el.width() > parentWidth){
fontSize--;
el.css('font-size', fontSize+'px');
el.css('margin-top', (parentHeight-fontSize)/2-1+'px');
console.log('margin-top: ', parentHeight, fontSize);
}
el.css('width', parentWidth+'px');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment