I want to create a simple light/dark mode system with javascript. It works by setting the 'darkTheme' boolean in Window.localStorage Here is the code I wrote:
let lightThemeCheckbox = document.getElementById('lightThemeCheckbox');
let body = document.body;
updateLightTheme();
lightThemeCheckbox.addEventListener('change', function() {
Window.localStorage.setItem('darkTheme', this.checked);
});
function updateLightTheme() {
let darkTheme = window.localStorage.getItem('darkTheme');
if(darkTheme == undefined) {
body.style.backgroundColor = 'rgb(255, 255, 255)';
return;
}
body.style.backgroundColor = darkTheme ? 'rgb(100, 100, 100)' : 'rgb(255, 255, 255)';
}
But for some reason, I get this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'setItem')
at HTMLInputElement.<anonymous> (header.js:7)
(anonymous) @ header.js:7
Can anyone help?
You have put "window" with a capital w. You can use the following:
windowconst lightThemeCheckbox = document.getElementById('lightThemeCheckbox');
const body = document.body;
updateLightTheme();
lightThemeCheckbox.addEventListener('change', () => {
window.localStorage.setItem('darkTheme', this.checked);
});
function updateLightTheme() {
const darkTheme = window.localStorage.getItem('darkTheme');
if (darkTheme == undefined) {
body.style.backgroundColor = 'rgb(255, 255, 255)';
return;
}
body.style.backgroundColor = darkTheme ? 'rgb(100, 100, 100)' : 'rgb(255, 255, 255)';
}
localStorage without windowconst lightThemeCheckbox = document.getElementById('lightThemeCheckbox');
const body = document.body;
updateLightTheme();
lightThemeCheckbox.addEventListener('change', () => {
localStorage.setItem('darkTheme', this.checked);
});
function updateLightTheme() {
const darkTheme = localStorage.getItem('darkTheme');
if (darkTheme == undefined) {
body.style.backgroundColor = 'rgb(255, 255, 255)';
return;
}
body.style.backgroundColor = darkTheme ? 'rgb(100, 100, 100)' : 'rgb(255, 255, 255)';
}
Hoped this helped!