skip to Main Content

I have a simple toggle on my website, which when clicked adds/removes a class of .dark-mode on the html tag. Allows the colours of the page to invert.

The website is a simple, static website as that’s all it needs to be right now.

My question is, is it possible for the last mode to be ‘saved’ so if I user returns the browser remembers and displays that mode by default?

If so, I’m not sure what the method would be for this – so apologies for the terminology (or lack of it)!

const html = document.querySelector('html');
const button = document.querySelector('.contrast-toggle');

button.addEventListener('click', e => {
  e.preventDefault();
  html.classList.toggle('dark-mode');
});
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  width: 100%;
}

body {
  background: white;
  color: black;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: "Arial", sans-serif;
}

a,
a:visited,
a:focus,
a:hover,
a:active {
  color: black;
  text-decoration: none;
}

html.dark-mode body {
  background: black;
  color: white;
}

html.dark-mode a,
html.dark-mode a:visited,
html.dark-mode a:focus,
html.dark-mode a:hover,
html.dark-mode a:active {
  color: white;
}
<html>

<body>
  <p><a href="#" class="contrast-toggle">Click to Toggle</a></p>
</body>

</html>

2

Answers


  1. One way of doing that is storing the theme mode in your sessionStorage.

        const html = document.querySelector('html');
        const button = document.querySelector('.contrast-toggle');
        const initTheme = sessionStorage.getItem('dark-mode');
    
        if (initTheme === 'true') {
            html.classList.add('dark-mode');
        }
    
        button.addEventListener('click', e => {
            e.preventDefault();
            html.classList.toggle('dark-mode');
    
            sessionStorage.setItem('dark-mode', html.classList.contains('dark-mode'));
        });
    

    *If the browser’s sessionStorage though gets cleared, this won’t be maintained. A more permanent solution would be to have an API that stores the value in a DB per user (something like userPreferences)

    Login or Signup to reply.
  2. You are going to need JavaScript, check out LocalStorage

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search