Advertisement
Guest User

StackOverflow q:71798689 [js]

a guest
Apr 8th, 2022
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //if set to true, any operation involving localStorage will be excluded
  2. let securityFlag = false;
  3.  
  4. /**----------------------------------------------------------------------------------------------------------------------
  5.  *
  6.  * What follows are the functions governing the logic of our html page:
  7.  *
  8.  * initCheckboxStateBasedOnLocalStorage(checkbox)
  9.  * initAllCheckboxesStateBasedOnLocalStorage()
  10.  * onCheckBoxStateChange(event)
  11.  * addCheckboxLabelPair()
  12.  * cleanLocalStorage()
  13.  * pageReload()
  14.  * countHowManyCheckboxStored()
  15.  * main()
  16.  *
  17.  *--------------------------------------------------------------------------------------------------------------------**/
  18.  
  19. /**
  20.  * Initialize the checkbox state according to what's stored on localStorage and trigger its change event
  21.  * if the checkbox isn't known to localStorage, it gets added to it with a default value = false
  22.  */
  23. function initCheckboxStateBasedOnLocalStorage(checkbox){
  24.      
  25.     //if securityFlag is true, skip the operation
  26.     if(securityFlag) return;
  27.  
  28.     //retrieves the value stored in localStorage paired to the id passed
  29.     let valueStored = window.localStorage.getItem(checkbox.id);
  30.     //if valueStored is set
  31.     if(valueStored == 'true' || valueStored == 'false'){
  32.         //sets the checkbox value with what was retrieved from localStorage
  33.         checkbox.checked = valueStored == 'true' ? true : false;
  34.         //this is needed to trigger the change event on checkbox so that it will run its logic to  hide/show its label
  35.         checkbox.dispatchEvent(new Event('change'));
  36.     }
  37.     //otherwise, it means (maybe) the page didn't run yet before, so...
  38.     else{
  39.         //just make sure the checkbox is set to unchecked (not needed but to make things clear)
  40.         checkbox.checked = false;
  41.         //set the value false inside the corresponding key in the localStorage so next time the page runs it will read that
  42.         window.localStorage.setItem(checkbox.id, 'false');
  43.         //triggers the change event on the checkbox (but it's not needed because there's nothing to update in terms of visible labels)
  44.         checkbox.dispatchEvent(new Event('change'));
  45.     }
  46. }
  47.  
  48. /**
  49.  * Initialize all the checkboxes existing in the page now
  50.  */
  51. function initAllCheckboxesStateBasedOnLocalStorage(){
  52.   //for each of the checkboxes on the page
  53.   document.querySelectorAll('input[type="checkbox"]').forEach( (checkbox, i) => {
  54.     //initialize the current checkbox
  55.     initCheckboxStateBasedOnLocalStorage(checkbox);
  56.   });
  57. }
  58.  
  59. /**
  60.  * Will hide/show the label corresponding to checkbox that triggered the change event, and will save its value on localStorage
  61.  * It will be registered as the handler of the change event of every checkbox in the page
  62.  */
  63. function onCheckBoxStateChange(event){
  64.  
  65.     //event.target is the checkbox that triggered the event
  66.     let checkbox = event.target;
  67.  
  68.     //guesses the id of the label dedicated to the checkbox triggering the event
  69.     let msgContainer = document.getElementById(`label-${checkbox.id}`);
  70.     //if this checkbox is checked,
  71.     if (checkbox.checked){
  72.         //show the corresponding label
  73.         msgContainer.style.display = "block";
  74.         //if securityFlag is true, skip the operation
  75.         if(securityFlag) return;
  76.         //sets the state in localStorage for this.id
  77.         window.localStorage.setItem(checkbox.id ,true);
  78.     }
  79.     //otherwise
  80.     else{
  81.         //hide the corresponding label
  82.         msgContainer.style.display = "none";
  83.         //if securityFlag is true, skip the operation
  84.         if(securityFlag) return;
  85.         //sets the state in localStorage for this.id
  86.         window.localStorage.setItem(checkbox.id ,false);
  87.     }
  88. }
  89.  
  90. /**
  91.  * Add a checkbox-label pair to the page
  92.  */
  93. function addCheckboxLabelPair(){
  94.  
  95.     //query the document to know how many checkbox are there
  96.     let nrCheckboxes = document.querySelectorAll('input[type="checkbox"]').length;
  97.  
  98.     //sets the index of this new checkbox as +1
  99.     let i = nrCheckboxes + 1;
  100.  
  101.     //select and clone the template
  102.     var template = document.querySelector('template');
  103.     var clone = template.content.cloneNode(true);
  104.    
  105.     //set the parameters of the template so that the new clone will fit as the i-th element in the space
  106.     let p = clone.firstElementChild;
  107.     p.innerText = `checkbox${i}`;
  108.     let checkbox = clone.querySelector('input[type="checkbox"]');
  109.     checkbox.id = `ck${i}`;
  110.     let label = clone.querySelector('#label-ck');
  111.     label.id = `label-ck${i}`;
  112.     label.innerText = `Label bound to checkbox${i}`;
  113.        
  114.     //append the new crafted clone element to the body page
  115.     let body = document.querySelector("body");
  116.     body.appendChild(clone);
  117.  
  118.     //initialize the new checkbox
  119.     initCheckboxStateBasedOnLocalStorage(checkbox);
  120. }
  121.  
  122. /**
  123.  * Reset the localStorage so that there's no more memory of any previous state
  124.  */
  125. function cleanLocalStorage(){
  126.     localStorage.clear();
  127. }
  128.  
  129. /**
  130.  * Reload the page
  131.  */
  132. function pageReload(){
  133.     location.reload();
  134. }
  135.  
  136. /**
  137.  * Return the number of checkbox states saved in the localStorage
  138.  */
  139. function countHowManyCheckboxStored(){
  140.     return Object.keys(localStorage).length;
  141. }
  142.  
  143. /**
  144.  * Run this in your page js global context to include the logic needed to hide/show
  145.  * labels bound to checkboxes existing in your html dom
  146.  */
  147. function main(){
  148.  
  149.     //When the document has been loaded
  150.     document.addEventListener("DOMContentLoaded", function() {
  151.         //for each of the checkboxes on the page
  152.         document.querySelectorAll('input[type="checkbox"]').forEach( (checkbox, i) => {
  153.             //attach an handler to the event change
  154.             checkbox.addEventListener("change", onCheckBoxStateChange );
  155.         });
  156.  
  157.         //now reflect the value of checkboxes according to what's stored on localStorage
  158.         initAllCheckboxesStateBasedOnLocalStorage();
  159.  
  160.         //show the number of checkbox states saved in the local storage
  161.         document.querySelector('#stored_states_count').innerText = countHowManyCheckboxStored();
  162.     });
  163. }
  164.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement