Search code examples
javascriptlocal-storagedarkmode

Store dark mode in localStorage across web-pages


Salutations! I'm developing a new blog and, as the title suggests, I'm trying to store my Dark Mode style-sheet in localStorage across web-pages. Currently if a user selects Dark Mode, but then refreshes the page or links to another web-page, the site reverts back to Light Mode again. I want it to remember the user's choice of mode (Light or Dark). This is my current JavaScript code:

function swapStylesheet(sheet) {
document.getElementById('swap').setAttribute('href', sheet); 
}

How might I apply localStorage to this code so that the browser remembers which style-sheet the user chose?

Thank you so much!


Solution

  • It's fairly easy using localStorage API.

    In order to save to local storage:

    function swapStylesheet(sheet) {
    document.getElementById('swap').setAttribute('href', sheet); 
    localStorage.setItem('swap', sheet);
    }
    

    To retrive from local storage:

    function getLocalStorageSwapStyle(){
    let style=localStorage.getItem('swap');
    swapStyleSheet(style);
    }
    

    You may call getLocalStorageSwapStyle whenever you want. E.g: on page load or some certain event.

    More info regarding localStorage API can be found here: mdn