简体   繁体   中英

Saving JQuery Toggle State with Cookie

I've got an iFrame that is toggled either visible or hidden on button click. I'm using the JQuery .toggle function to do this. Currently the div for the area is hidden by default through CSS: style="display:none"

A new requirement has come in asking that the user's most recent show or hide (the selected toggle-state) be saved for the next page load, so if they chose to show the iFrame last time they were at the home page, the next time they visited it would be visible by default. I want to set the last selected toggle state with a cookie, but I can't get it to work. Below is my code:

<meta charset="utf-8">
<title>drop demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<style>
  #toggle {
    width: 100px;
    height: 100px;
    background: #ccc;
  }
  .button {
    padding-top: 10px;
    padding-right: 20px;
  }
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<button type="button" id="button"
title="Personalized Sales Dashboard">Show/Hide</button>
<div id="toggle" style="display:none" frameborder="2">
<iframe src="https://sample.com"="" id="myfr" scrolling="no" frameborder="0"
 height="800px" width="100%">Your Browser Do not Support Iframe</iframe>
</div>
<script>
  $("#button").click(function () {
    $("#toggle").toggle("blind");
  });
  $(function () {
    $("#button").tooltip();
  });
</script>

Set a cookie on your button click whether the div is visible:

document.cookie = "toggleState=" + $("#toggle").is(':visible');

And retrieve it on page load, showing or hiding the content accordingly:

var toggleState = document.cookie.replace(/(?:(?:^|.*;\s*)toggleState\s*\=\s*([^;]*).*$)|^.*$/, "$1");

if (toggleState == 'true') {
    $("#toggle").show();
}
else {
    $("#toggle").hide();
}

https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM