Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //if set to true, any operation involving localStorage will be excluded
- let securityFlag = false;
- /**----------------------------------------------------------------------------------------------------------------------
- *
- * What follows are the functions governing the logic of our html page:
- *
- * initCheckboxStateBasedOnLocalStorage(checkbox)
- * initAllCheckboxesStateBasedOnLocalStorage()
- * onCheckBoxStateChange(event)
- * addCheckboxLabelPair()
- * cleanLocalStorage()
- * pageReload()
- * countHowManyCheckboxStored()
- * main()
- *
- *--------------------------------------------------------------------------------------------------------------------**/
- /**
- * Initialize the checkbox state according to what's stored on localStorage and trigger its change event
- * if the checkbox isn't known to localStorage, it gets added to it with a default value = false
- */
- function initCheckboxStateBasedOnLocalStorage(checkbox){
- //if securityFlag is true, skip the operation
- if(securityFlag) return;
- //retrieves the value stored in localStorage paired to the id passed
- let valueStored = window.localStorage.getItem(checkbox.id);
- //if valueStored is set
- if(valueStored == 'true' || valueStored == 'false'){
- //sets the checkbox value with what was retrieved from localStorage
- checkbox.checked = valueStored == 'true' ? true : false;
- //this is needed to trigger the change event on checkbox so that it will run its logic to hide/show its label
- checkbox.dispatchEvent(new Event('change'));
- }
- //otherwise, it means (maybe) the page didn't run yet before, so...
- else{
- //just make sure the checkbox is set to unchecked (not needed but to make things clear)
- checkbox.checked = false;
- //set the value false inside the corresponding key in the localStorage so next time the page runs it will read that
- window.localStorage.setItem(checkbox.id, 'false');
- //triggers the change event on the checkbox (but it's not needed because there's nothing to update in terms of visible labels)
- checkbox.dispatchEvent(new Event('change'));
- }
- }
- /**
- * Initialize all the checkboxes existing in the page now
- */
- function initAllCheckboxesStateBasedOnLocalStorage(){
- //for each of the checkboxes on the page
- document.querySelectorAll('input[type="checkbox"]').forEach( (checkbox, i) => {
- //initialize the current checkbox
- initCheckboxStateBasedOnLocalStorage(checkbox);
- });
- }
- /**
- * Will hide/show the label corresponding to checkbox that triggered the change event, and will save its value on localStorage
- * It will be registered as the handler of the change event of every checkbox in the page
- */
- function onCheckBoxStateChange(event){
- //event.target is the checkbox that triggered the event
- let checkbox = event.target;
- //guesses the id of the label dedicated to the checkbox triggering the event
- let msgContainer = document.getElementById(`label-${checkbox.id}`);
- //if this checkbox is checked,
- if (checkbox.checked){
- //show the corresponding label
- msgContainer.style.display = "block";
- //if securityFlag is true, skip the operation
- if(securityFlag) return;
- //sets the state in localStorage for this.id
- window.localStorage.setItem(checkbox.id ,true);
- }
- //otherwise
- else{
- //hide the corresponding label
- msgContainer.style.display = "none";
- //if securityFlag is true, skip the operation
- if(securityFlag) return;
- //sets the state in localStorage for this.id
- window.localStorage.setItem(checkbox.id ,false);
- }
- }
- /**
- * Add a checkbox-label pair to the page
- */
- function addCheckboxLabelPair(){
- //query the document to know how many checkbox are there
- let nrCheckboxes = document.querySelectorAll('input[type="checkbox"]').length;
- //sets the index of this new checkbox as +1
- let i = nrCheckboxes + 1;
- //select and clone the template
- var template = document.querySelector('template');
- var clone = template.content.cloneNode(true);
- //set the parameters of the template so that the new clone will fit as the i-th element in the space
- let p = clone.firstElementChild;
- p.innerText = `checkbox${i}`;
- let checkbox = clone.querySelector('input[type="checkbox"]');
- checkbox.id = `ck${i}`;
- let label = clone.querySelector('#label-ck');
- label.id = `label-ck${i}`;
- label.innerText = `Label bound to checkbox${i}`;
- //append the new crafted clone element to the body page
- let body = document.querySelector("body");
- body.appendChild(clone);
- //initialize the new checkbox
- initCheckboxStateBasedOnLocalStorage(checkbox);
- }
- /**
- * Reset the localStorage so that there's no more memory of any previous state
- */
- function cleanLocalStorage(){
- localStorage.clear();
- }
- /**
- * Reload the page
- */
- function pageReload(){
- location.reload();
- }
- /**
- * Return the number of checkbox states saved in the localStorage
- */
- function countHowManyCheckboxStored(){
- return Object.keys(localStorage).length;
- }
- /**
- * Run this in your page js global context to include the logic needed to hide/show
- * labels bound to checkboxes existing in your html dom
- */
- function main(){
- //When the document has been loaded
- document.addEventListener("DOMContentLoaded", function() {
- //for each of the checkboxes on the page
- document.querySelectorAll('input[type="checkbox"]').forEach( (checkbox, i) => {
- //attach an handler to the event change
- checkbox.addEventListener("change", onCheckBoxStateChange );
- });
- //now reflect the value of checkboxes according to what's stored on localStorage
- initAllCheckboxesStateBasedOnLocalStorage();
- //show the number of checkbox states saved in the local storage
- document.querySelector('#stored_states_count').innerText = countHowManyCheckboxStored();
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement