I am attempting to create a function using only vanilla JS which will resize fonts in a container with a given class. Found this demo, which seems as though it would do the trick. Unfortunately, their 'Javascript' version actually uses the $() jquery selector to target the specific element in the DOM, based upon both its element type and class.
As vanilla JS does not allow for this, I'm unsure how to apply the solution.
The logic is confusing me where I need to target the element exactly and may have multiple instances of the same element with the same class, which all need to be processed separately.
i.e. I might have two h3 elements with the '.resize' class attached, but the first element is 50px by 100px and the second is 200px by 400px. If I simply applied the solution based on the generic element type and class ,then the css rule generated for the second element would also be applied to the first.
The only way I can think to do it is to use a unique ID for each element instead of the '.replace' class, then create an array containing the pre-defined IDs and iterate over the array to target each element. This solution is not elegant or scalable.
I have modified the function to target the .style.fontSize
attribute using only vanilla JS, but now I get an infinite loop.
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;
}
Vanilla JS does not allow for this, but browser flavoured Vanilla JS does. It's called document.querySelector
(docs) and document.querySelectorAll
(docs).
Examples from the documentation:
In this example, the first element in the document with the class "myclass" is returned:
var el = document.querySelector(".myclass");
This example returns a list of all div elements within the document with a class of either "note" or "alert":
var matches = document.querySelectorAll("div.note, div.alert");