Attempting to set up a simple dark mode function that persists. The dark mode itself works, but can't hide button display (they will only hide once clicked on and the function is triggered).
Edit: I should clarify - the issue I am having is getting the button to stay hidden on refresh/when I click to a different page. The dark mode remains (black background & white text) but the button reappears until I click it again.
In my console I am getting the following error - Uncaught TypeError: Cannot read properties of null (reading 'style') at js:27:36
Apologies I am new to JavaScript
var body = document.querySelector("body");
var theme = localStorage.getItem('darkmode');
function dark() {
body.style.color = 'white';
body.style.backgroundColor = 'black';
document.getElementById('dark').style.display = 'none';
document.getElementById('light').style.display = 'block';
localStorage.setItem('darkmode', true);
}
function light() {
body.style.color = 'black';
body.style.backgroundColor = 'white'
document.getElementById('light').style.display = 'none';
document.getElementById('dark').style.display = 'block';
localStorage.setItem('darkmode', false);
}
if (theme == "true") {
body.style.color = 'white';
body.style.backgroundColor = 'black';
document.getElementById('dark').style.display = 'none';
document.getElementById('light').style.display = 'block';
} else if (theme == "false") {
body.style.color = 'black';
body.style.backgroundColor = 'white'
document.getElementById('light').style.display = 'none';
document.getElementById('dark').style.display = 'block';
}
<a id='dark' class='navbar-link' href="#" onclick="dark()" role="button">Darkmode!</a>
<a id='light' class='navbar-link' href="#" onclick="light()" role="button">Lightmode!</a>
Seems to be a getElementByID issue as the rest of the if function works as expected, not sure if this has to be triggered by a function call or if there is an alternative.