Search code examples
jquerylocal-storagepage-refresh

store theme colour with jQuery


HTML part

<div class="theme_toggle">
    <div class="theme_toggle_light">
         <img src="assets/images/light.png" alt="" class="theme_toggle_img">
    </div>
    <div class="theme_toggle_dark">
          <img src="assets/images/dark.png" alt="" class="theme_toggle_img">
    </div>
</div>

jquery part

$('.theme_toggle_dark').click(function () {
     $('body').attr('class', 'dark');
 })
 $('.theme_toggle_light').click(function () {
     $('body').removeClass('dark');
 })

I want that when I refresh the page if the dark class is added to the body it should be stored and if I press to remove the dark class then it should be removed.


Solution

  • Use local storage.

    $('.theme_toggle_dark').click(function() {
      $('body').addClass('dark');
      localStorage.setItem('darkClass', 'true');
    });
    
    $('.theme_toggle_light').click(function() {
      $('body').removeClass('dark');
      localStorage.removeItem('darkClass');
    });
    
    // Check if the 'darkClass' item exists in local storage on page load
    if (localStorage.getItem('darkClass') === 'true') {
      $('body').addClass('dark');
    }
    

    This will set the darkClass item in local storage to true when the dark class is added to the body, and remove the item from local storage when the dark class is removed.

    On page load, the code will check for the presence of the darkClass item in local storage, and reapply the dark class to the body if it exists.