Advertisement
Guest User

Untitled

a guest
Oct 7th, 2021
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.         // Avoid scoping issues by encapsulating
  2.         // code inside anonymous function
  3.         (function () {
  4.             // variable to store our current state
  5.             var cbstate;
  6.  
  7.             // bind to the onload event
  8.             window.addEventListener('load', function () {
  9.                 // Get the current state from localstorage
  10.                 // State is stored as a JSON string
  11.                 cbstate = JSON.parse(localStorage['CBState'] || '{}');
  12.  
  13.                 // Loop through state array and restore checked
  14.                 // state for matching elements
  15.                 for (var i in cbstate) {
  16.                     var el = document.querySelector('input[name="' + i + '"]');
  17.                     if (el) el.checked = true;
  18.                 }
  19.  
  20.                 // Get all checkboxes that you want to monitor state for
  21.                 var cb = document.getElementsByClassName('save-cb-state');
  22.  
  23.                 // Loop through results and ...
  24.                 for (var i = 0; i < cb.length; i++) {
  25.  
  26.                     //bind click event handler
  27.                     cb[i].addEventListener('click', function (evt) {
  28.                         // If checkboxe is checked then save to state
  29.                         if (this.checked) {
  30.                             cbstate[this.name] = true;
  31.                         }
  32.  
  33.                         // Else remove from state
  34.                         else if (cbstate[this.name]) {
  35.                             delete cbstate[this.name];
  36.                         }
  37.  
  38.                         // Persist state
  39.                         localStorage.CBState = JSON.stringify(cbstate);
  40.                     });
  41.                 }
  42.             });
  43.         })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement