Setting keeping the result of an interaction on reload

Hey there,

I am trying to add a darkmode on my website using a custom attribute. This works by defining a [data-theme=“dark”] in the style.css

The toggle button then uses this interaction to switch between the modes:

This works very well, but the problem is that the attribute is removed whenever I reload the page or go to a different page. This obviously doesn´t work for a darkmode.

I am surprised nobody asked about this before, but is there a way to save the result of an interaction in a cookie so it will stay applied even when switching pages or reloading?

Thanks for your help!
Adrian

1 Like

Probably can only be done through js

Phew I have no experience with Javascript, that will be difficult. But thank you.

Uuuuhh… I am at the same point! Hopefully someone can help out!

I found this in another post of the forum, but still dont know how to achieve that…

“When clicking on the element, I save a the language-code in the LocalStorage via the interaction in order to automatically point to the chosen language when visiting the page later.”

This solution add class “dark-theme” to body tag. Changes is saved in LocalStorage

    <script>
        const body = document.body;
        const toggleThemeLink = document.getElementById('toggle-theme');
        const savedTheme = localStorage.getItem('theme') || 'light';

        function setTheme(theme) {
            body.classList.toggle('dark-theme', theme === 'dark');
            localStorage.setItem('theme', theme);
        }

        function toggleTheme() {
            const newTheme = savedTheme === 'light' ? 'dark' : 'light';
            setTheme(newTheme);
        }

        toggleThemeLink.addEventListener('click', toggleTheme);
        setTheme(savedTheme);
    </script>

link for change style

<a href="#" id="toggle-theme">Change style</a>