Skip to content

Instantly share code, notes, and snippets.

@scizers
Created January 23, 2015 19:21
Show Gist options
  • Save scizers/64de35c0e29b33b238ca to your computer and use it in GitHub Desktop.
Save scizers/64de35c0e29b33b238ca to your computer and use it in GitHub Desktop.
autofit text angaularjs directive
app.directive('autofit', function(){
return function(scope, element, attrs){
var span = element.find('span:visible:first');
var maxHeight = element.height();
var maxWidth = element.width();
var originalFontSize = parseInt(element.css('font-size').replace('px',''),10);
function resize(){
var fontSize = originalFontSize;
var textHeight = span.height();
var textWidth = span.width();
do {
element.css('font-size', fontSize + 'px');
//span.css('line-height', fontSize + 'px');
element.css('line-height', fontSize + 'px');
textHeight = span.height();
textWidth = span.width();
fontSize--;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
}
if(attrs.autofit){
var parts = attrs.autofit.split(',');
for(var i in parts){
scope.$watch(parts[i], function(){
resize();
});
}
}
resize();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment