I am struggling to create a vanilla JS function that will resize fonts in a container with a specified class. I came across this demo, which seemed promising. However, the 'Javascript' version uses the $() jquery selector to target elements, making it incompatible with vanilla JS.
Since vanilla JS does not support this method, I am unsure how to proceed with implementing the solution.
The complexity arises when I have multiple instances of the same element with the same class that need to be processed individually. For example, if I have two h3 elements with the '.resize' class, each with different dimensions, applying a generic solution would cause conflicts.
One approach I considered was using unique IDs for each element instead of the '.replace' class, then creating an array of these IDs to iterate over and target each element. However, this solution is neither elegant nor scalable.
I attempted to modify the function to target the .style.fontSize
attribute exclusively within vanilla JS, but encountered an infinite loop issue.
JS:
function autoSize () {
var el, elements, _i, _len, _results;
elements = document.getElementsByClassName('resize');
console.log(elements);
if (elements.length < 0) {
return;
}
_results = [];
for (_i = 0, _len = elements.length; _i < _len; _i++) {
el = elements[_i];
_results.push((function(el) {
var resizeText, _results1;
resizeText = function() {
var elOldFontSize = el.style.fontSize;
var elNewFontSize;
elNewFontSize = (parseInt(elOldFontSize.slice(0, -2)) - 1) + 'px';
el.style.fontSize = elNewFontSize;
};
_results1 = [];
while (el.scrollHeight > el.offsetHeight) {
_results1.push(resizeText());
}
return _results1;
})(el));
}
return _results;
}