Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Day/Night Toggle Using Cookie to Save on Page Refresh

The problem I'm having of course is the toggle cookie is always true once the toggle is clicked. Is there a way to check whether the toggle is active / inactive and to save that state to a cookie to then check on page refresh if dark mode should be activated?

jQuery(document).ready(function($) {
  $(".toggle").click(function() {
    $(".toggle").toggleClass("active");
    $("body").toggleClass("night");
    $.cookie("toggle", true);
  });

  if ($.cookie("toggle") == "true") {
    $(".toggle").click();
  }
});
body.night {
  background: #00151f;
  color: #fff;
}

.toggle {
  position: absolute;
  top: 40px;
  left: 0px;
  background: #fff;
  border: 2px solid #00151f;
  width: 45px;
  height: 20px;
  cursor: pointer;
  border-radius: 20px;
  transition: 0.5s;
}

.toggle.active {
  background: #00151f;
  border: 1px solid #fff;
}

.toggle:before {
  left: 0px;
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  background: #00151f;
  border-radius: 50%;
  transition: 0.5s;
}

.toggle.active:before {
  left: 27px;
  background: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle"></div>
like image 970
wormyworm Avatar asked Oct 28 '25 08:10

wormyworm


1 Answers

The issue is because you only ever set the cookie to true, even when changing the state. To fix this use hasClass() to determine what state the UI is in and set the cookie accordingly:

jQuery(document).ready(function($) {
  $(".toggle").click(function() {
    $(".toggle").toggleClass("active");
    $("body").toggleClass("night");
    $.cookie("toggle", $(".toggle").hasClass('active'));
  });

  if ($.cookie("toggle") === "true") {
    $(".toggle").addClass("active");
    $("body").addClass("night");
  }
});

Example fiddle

like image 166
Rory McCrossan Avatar answered Oct 30 '25 23:10

Rory McCrossan