I'm trying to implement a font changer for my website with JavaScript and , but the header iteration part won't work.
undefined is not an object (evaluating 'tagElement.style.fontFamily = fontsObj.headerFont')
Here's my code
HTML:
<select name="font-select" id="font-select">
<option value='{"headerFont":"system-ui, -apple-system","bodyFont":"system-ui, -apple-system"}'>System & System</option>
<option value='{"headerFont":"Lato","bodyFont":"Karla"}' selected="selected">Lato & Karla</option>
<option value='{"headerFont":"Lora","bodyFont":"Lato"}'>Lora & Lato</option>
<option value='{"headerFont":"Philosopher","bodyFont":"Mulish"}'>Philosopher & Muli(sh)</option>
</select>
JS:
function changeFontStyle(fonts) {
const headerTags = ["h1", "h2", "h3", "h4", "h5", "h6"];
var bodyText;
const fontsObj = JSON.parse(fonts.value);
// Update headers' font
for (let headerTag in headerTags) {
var tagElements = document.getElementsByTagName(headerTag);
for (let tagElement in tagElements) {
tagElement.style.fontFamily = fontsObj.headerFont;
}
}
// Update body font
bodyText = document.getElementsByTagName("html")[0];
bodyText.style.fontFamily = fontsObj.bodyFont;
}
var fontSelector = document.getElementById("font-select")
fontSelector.onchange = changeFontStyle(fontSelector);
The JSON.parse part seems to work right (as opposed to comments below this answer), at least I can't see any parse errors.
Edit: Newest version of question here