Day/Night Toggle Using Cookie to Save on Page Refresh

久未见 提交于 2021-02-09 18:36:28

问题


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>

回答1:


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



来源:https://stackoverflow.com/questions/54326422/day-night-toggle-using-cookie-to-save-on-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!