I have a container (with a background image) and inside this container there is some text (chosen by reading value from a text input). To fit the text I’m using textFit script. User can also choose the font and there is the major problem.
For reference I’m putting some code:
<input type="text" id="ChosenText" autocomplete="off" placeholder="Type text here" oninput="refreshPicture()">
<select id="ChosenFont" onchange="changeFontFamily(true)">/*options are generated by JS*/</select>
<div id="slide-container">
<span id="textOnPicture" class="textOnPicture textFitted">/*here JS puts text from an input*/</span>
</div>
const resultContainer = document.querySelector("#slide-container");
const chosenText = document.querySelector("#ChosenText");
const chosenFont = document.querySelector("#ChosenFont");
const textOnPicture = document.querySelector(".textOnPicture");
function refreshPicture() {
textOnPicture.textContent = chosenText.value;
textFit(resultContainer);
}
async function reloadPicture(manualChoose) { //function is called by pressing "Reload" button and it is async because when it isn't, picture doesn't display for unknown reason
await changeFontFamily(manualChoose); //here is the thing, I want to change font family
refreshPicture();
}
function changeFontFamily(manualChoose) {
let fontFamily;
if (!!manualChoose) {//when triggered by changing value of input
fontFamily = chosenFont.value;
textOnPicture.style.setProperty("--font-family", fontFamily); //in css this property is obviously assigned to font-family of textOnPicture
textFit(resultContainer);
} else {//when triggered by "Reload" button, then random picture, font and color are chosen
fontFamily = fonts[Math.floor(Math.random() * fonts.length)].name;
textOnPicture.style.setProperty("--font-family", fontFamily);
chosenFont.value = fontFamily;
}
}
The problem is when I change font family (by pressing the button and choosing it randomly or manually by changing value) font size doesn’t change and sometimes text is outside of the container. But when I call textFit function again it fixes.
“await” before changeFontFamily function should wait until funtion finish its work, right? So why it isn’t? textFit is called after that but it seems like browser is doing it in wrong order or textFit ignores that font has been changed.
Due to every font family basically has its own size the text is sometimes too small or too big after change of font family and it looks terrible. Of course I would like to my text always have correct size.