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");
}));
3
Answers
The issue in your code is that you are trying to access the value of –mFont from localStorage before it is set. When your code first runs, the localStorage.getItem("–mFont") will return null because the item has not been set yet. When you try to add null to a number using parseInt, it will return NaN. That’s why you are seeing NaNpx instead of the correct number.
To fix this issue, you need to set a default value for –mFont if it is not already in localStorage. You can do this by using the logical OR (||) operator to provide a default value if localStorage.getItem("–mFont") returns null.
It looks like the issue might be with the line:
This line is attempting to parse the stored font size value from localStorage as an integer, but the stored value includes the "px" suffix, so the parsing returns NaN (Not a Number).
To fix this, you can modify the line to extract only the numeric value from the stored string value by using the parseInt() function with a radix of 10, and then add the button value and the "px" suffix:
This should correctly calculate and set the new font size value with the correct unit.
Initially there is no set value in the
localStorage
, so you’re callingparseInt(null)
, which results inNaN
. You can usegetComputedStyle
on the root element instead to get the actual current--mfont
value.