Skip to content
Advertisement

Toggle localstorage item in Svelte

new to Svelte so excuse the little knowledge.

I am attempting to save a localStorage item on:click and toggle it when clicked again. Currently, the item is added to localStorage but on a second click, it is not removed. If you refresh the page and click the item is removed but I would like this not to be necessary.

Onclick event

JavaScript

Toggle Handling

JavaScript

Could someone please help me here? 🙂

Advertisement

Answer

This line is eveluated once when you open the page

JavaScript

When you click the first time, you write 'true' to localStorage, but the variable _ac_dyslexiaFriendlyFontToken stays the same and so when you click the second time you’ll land again in if (_ac_dyslexiaFriendlyFontToken == undefined)

_ac_dyslexiaFriendlyFontToken is null, but undefined == null // true since you have only two equal signs ~ it’s possible to simply check if(_ac_dyslexiaFriendlyFontToken) or if(!_ac_dyslexiaFriendlyFontToken) to check if the value is truthy or falsy
https://developer.mozilla.org/en-US/docs/Glossary/Truthy
https://developer.mozilla.org/en-US/docs/Glossary/Falsy

So to switch between the if(){}else{} change _ac_dyslexiaFriendlyFontToken in addition to writing to local storage

Here’s your modified example which also adds the class if the token is set in localStorage on opening the page

JavaScript

(_ac_dyslexiaFriendlyFontToken set as 'true' or null like the values from localStorage. Would also work with booleans true and false Not sure if there’s a convention to follow…)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement