I apologise in advance as I know this question has come up many times before but I just can\'t seem to find the right solution (and believe me I\'ve tried a few!)
Ba
Here's a slightly modified version of the given answers.
Requirements :
What changes in this version ?
Note:
I don't claim the code is production ready. But if you find something you can enhance, please share it with the community.
var autoSizeText = function () {
var el, elements, _i, _len;
elements = $('.resize');
if (elements.length < 0) {
return;
}
for (_i = 0, _len = elements.length; _i < _len; _i++) {
el = elements[_i];
dichoFit = function (el) {
diminishText = function () {
var elNewFontSize;
elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';
return $(el).css('font-size', elNewFontSize);
};
augmentText = function () {
var elNewFontSize;
elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) + 1) + 'px';
return $(el).css('font-size', elNewFontSize);
};
diminishText();
while (el.scrollHeight < el.offsetHeight) {
augmentText();
}
augmentText();
while (el.scrollHeight > el.offsetHeight) {
diminishText();
}
}
dichoFit(el);
}
};
$(document).ready(function () {
autoSizeText();
$(window).resize(function resizeText(){
autoSizeText()
})
});
.sizable{
width: 50vw;
height: 50vh;
border: 2px solid darkred;
}
I am a sizable div and I have explicit width and height.