I'm trying to write a script in Javascript that will change the property of a CSS variable that determines the body's font size, based on a button click, that will then save to localstorage. I've referenced answers given in increase / decrease font size and store in cookie and How to store CSS variables in the browser memory and wrote a script that seemed to work in my text editor, but when implemented returned NaNpx
instead of the correct number. This is my first foray into Javascript, so I'm not sure what went wrong. Any insight would be appreciated.
The CSS:
body { background-color: #888; font-size: var(--mfont); transition: font-size .25s ease-in-out; }
:root { --mfont: 20px; --xxlfont: calc(var(--mfont) + 3px); --xxsfont: calc(var(--mfont) - 3px); }
The HTML:
<p>test</p>
<p style="font-size: var(--xxlfont)">xxl test</p>
<p style="font-size: var(--xxsfont)">xxs test</p>
<button class="fontbutton" type="button" value="-1" title="Decrease font size">A-</button>
<button class="fontbutton" type="button" value="1" title="Increase font size">A+</button>
The Javascript:
const root = document.querySelector(":root");
const fontbutton = document.querySelectorAll(".fontbutton");
if(localStorage.getItem("--mFont") != null) {
root.style.setProperty("--mfont", localStorage.getItem("--mFont"));
};
fontbutton.forEach(el => el.addEventListener("click", function() {
root.style.setProperty("--mfont", parseInt(localStorage.getItem("--mFont")) + parseInt(this.value) + "px");
localStorage.setItem("--mFont", parseInt(localStorage.getItem("--mFont")) + parseInt(this.value) + "px");
}));