0

I am trying to add dark-mode to the website. When someone clicks the dark mode button it will add additional CSS classes and remove them when the button is clicked again.

I know I can do it easily with toggleClass but I don't want to disable this automatically when the page refreshes or some other page is opened on the website.

I have been playing with sessionStorage but unable to succeed so far I have come up with this code here:

<a href="#" class="darkmode-button" id="dmbutton" onclick="changeText()">Dark Mode</a>

<div class="header-wrap">
  Testing toggle with session
</div>
$('.darkmode-button').click(function() {
  if (sessionStorage.getItem('darkmode', 'true')) {
    $('.header-wrap').removeClass('dark-header');
    sessionStorage.setItem('darkmode', 'false');
  }
  
  if (sessionStorage.getItem('darkmode', 'false')) {
    $('.header-wrap').addClass('dark-header');
    sessionStorage.setItem('darkmode', 'true');
  }
});

function changeText() {
  var x = document.getElementById("dmbutton");
  if (x.innerHTML === "Dark Mode") {
    x.innerHTML = "Light Mode";
  } else {
    x.innerHTML = "Dark Mode";
  }
}
.header-wrap {
  color: black;
}

.dark-header {
  color: white;
  background-color: black;
}

Can someone please share a working example of how it can be achieved?

I already created a question before but it was marked duplicate with this answer. I read it all but still could not figure it out.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Bilal Naseer
  • 156
  • 1
  • 2
  • 16
  • _"I read it all but still could not figure it out"_ - well then you should at least be able to ask us some more _specific_ questions now, about what exactly is giving you trouble with this ...? I can't be the purpose of this site, that people ask the same thing over and over and over again, when good & quite extensive explanations on a topic already exist. – CBroe Sep 22 '22 at 13:17
  • Your fiddle doesnt even toggle dark mode so no surprise it doesnt store it. Did you check the browser console for errors? – Jaromanda X Sep 22 '22 at 13:18
  • I have added a JS fiddle about the attempt I made with sessionStorage – Bilal Naseer Sep 22 '22 at 13:18
  • https://jsfiddle.net/websensepro/k1cvunp4/12/ that's my progress if I remove if conditions of sessionStorage code works fine – Bilal Naseer Sep 22 '22 at 13:19
  • Code you are asking questions about, belongs directly into your question, not just dumped onto an external platform. – CBroe Sep 22 '22 at 13:20
  • First thing I see in concole in your fiddle, when clicking the link: _"Uncaught DOMException: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document."_ - that is likely due to the fact that is was presented on that platform, within the iframe where the results get rendered, some restrictions apply, that would not on a normal, not-iframed page. So this is not even all that suitable as a test environment in this particular case to begin with. – CBroe Sep 22 '22 at 13:22
  • Sorry I am new here, just added more explanation to my question – Bilal Naseer Sep 22 '22 at 13:22
  • @CBroe jsfiddle does not work with sessionStorage – Bilal Naseer Sep 22 '22 at 13:50

2 Answers2

0

To do what you require simply set a single class on a parent element, the body would work well in this case, to indicate when dark mode has been turned on. You can then use this class in all the relevant selectors in your CSS to update the UI.

Regarding the session storage logic, set a boolean flag when the dark mode is updated when the button is clicked and set the class on the body based on the session storage flag when the page loads.

Putting it all together would look something like this:

<a href="#" class="darkmode-button" id="dmbutton">Dark Mode</a>

<div class="header-wrap">
  Testing toggle with session
</div>
let body = document.body;
let dmButton = document.querySelector('#dmbutton');

dmButton.addEventListener('click', e => {
  body.classList.toggle('dark');
  sessionStorage.setItem('darkmode', body.classList.contains('dark'));
  e.target.textContent = e.target.textContent.trim() === 'Dark Mode' ? 'Light Mode' : 'Dark Mode';
});

let darkModeEnabled = JSON.parse(sessionStorage.getItem('darkmode')); // boolean type coercion
if (darkModeEnabled) {
  body.classList.add('dark');
  dmButton.textContent = 'Light Mode';
}
.header-wrap {
  color: black;
}

body.dark {
  background-color: #666; 
}

body.dark .header-wrap {
  color: white;
  background-color: black;
}

Here's a working example in a jsFiddle, as SO snippets are sandboxed and disallow local/session storage access.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

I don't know the logic of this code but it works for me which I found from this solution thanks to Stackoverflow

<a href="#" class="darkmode-button" id="dmbutton">Dark Mode</a>

<div class="header-wrap">
  Testing toggle with session
</div>
var $dark = $('.header-wrap')

if (localStorage.getItem('darkmode') === 'true') {
    $dark.addClass('dark-header');
}

$('.darkmode-button').click(function() {
    $dark.toggleClass('dark-header');
    localStorage.setItem('darkmode', $dark.hasClass('dark-header'));
});
.header-wrap {
  color: black;
}

.dark-header {
  color: white;
  background-color: black;
Bilal Naseer
  • 156
  • 1
  • 2
  • 16