Search code examples
javascriptlocal-storagecss-variables

How to change font size using CSS variables and localstorage


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");
}));

Solution

  • Initially there is no set value in the localStorage, so you're calling parseInt(null), which results in NaN. You can use getComputedStyle on the root element instead to get the actual current --mfont value.

    fontbutton.forEach(el => el.addEventListener("click", function() {
        const prevFont = getComputedStyle(root).getPropertyValue('--mfont');
        root.style.setProperty("--mfont", parseInt(prevFont) + parseInt(this.value) + "px");
        localStorage.setItem("--mFont", parseInt(prevFont) + parseInt(this.value) + "px");
    }));