Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading