Home > OS >  How to show/hide div with toggle in different page
How to show/hide div with toggle in different page

Time:04-10

I have toggle on the options page which should show / hide div on another page. With some help here on stack I was able to structure this code, but I can't get it to work.

Fiddle: https://jsfiddle.net/snake93/mLonrbkf/1/

  1. I can't show / hide the divs
  2. I don't understand how to save in localstorage

I would like to understand what values the functions of the Js code must assume. Can anyone help me?

function setSetting(name,value){
  window.localStorage.setItem(name,true);
}
function getSetting(name){
  return window.localStorage.getItem(name);
}

const div = document.querySelector("label-ck1");

if(getSetting("show")){
  div.style.display = "block";
}
else{
  div.style.display = "none";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<label >
  <input type="checkbox" id="ck1">
  <span ></span>
</label>
<br><br>

<label >
   <input type="checkbox" id="ck2">
   <span ></span>
</label>
<br><br>

<div  id="label-ck1">Please hide me...</div>
<div  id="label-ck2">Please hide me...</div>

CodePudding user response:

I copied what you wrote in your original code in jsfiddle using the same css I found there. Then I just rewrote the javascript part.

What it does is attaching a change event handler to any checkbox found on the page so that when their state it's changed, the corresponding label gets shown or hidden. The corresponding label is found using the checkbox id with the prefix label-.

In that event, the state of the checkbox changed gets pushed in the localStorage. At the very beginning, the page first checks if there's any state saved for each of the checkbox found and in case there is, its state gets updated correspondingly.

In Firefox localStorage methods (getItem/setItem) return SecurityError: The operation is insecure. I could run that code on a dedicated html page to verify it's working correctly (on Chrome for sure). So to avoid any problem at first, I added a securityFlag on top of the js code. When that flag is set to true, the localStorage won't be engaged at all so that you could see the preview here with no errors.

//if set to true, any operation involving localStorage will be excluded
let securityFlag = true;

/**
 * Initialize the Checkboxes state according to what's stored on localStorage
 */
function initCheckboxStateBasedOnLocalStorage(){
    //for each of the checkboxes on the page
    document.querySelectorAll('input[type="checkbox"]').forEach( (checkbox, i) => {
    
        //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;
    });
}

/**
 * Will hide/show the label corresponding to checkbox 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(){

    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);
    }
}

//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 );
  });
});

//reflect the value of checkboxed according to what's stored on localStorage
initCheckboxStateBasedOnLocalStorage();
.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
  }
  
  .switch input { 
    opacity: 0;
    width: 0;
    height: 0;
  }
  
  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
  }
  
  .slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
  }
  
  input:checked   .slider {
    background-color: #2196F3;
  }
  
  input:focus   .slider {
    box-shadow: 0 0 1px #2196F3;
  }
  
  input:checked   .slider:before {
    -webkit-transform: translateX(26px);
    -ms-transform: translateX(26px);
    transform: translateX(26px);
  }
  
  /* Rounded sliders */
  .slider.round {
    border-radius: 34px;
  }
  
  .slider.round:before {
    border-radius: 50%;
  }

/*END OF TOGGLE SWITCH*/

.hideme {
  padding:20px;
  background: blue;
  color: white;
  font-weight: 800;
  text-align: center;
}
<p>checkbox1</p>
<label >
  <input type="checkbox" id="ck1">
  <span ></span>
</label>

<br><br>

<p>checkbox2</p>
<label >    
   <input type="checkbox" id="ck2">
   <span ></span>
</label>
<br><br>

<div  id="label-ck1">Label bound to checkbox1</div>
<div  id="label-ck2">Label bound to checkbox2</div>

In case you need a fully workable solution out of the box, I uploaded a set of files on pastebin as being:

File Download link
demo.html https://pastebin.com/mHWQ7564
style.css https://pastebin.com/3jzTubFR
logic.js https://pastebin.com/uFDrGrZx

Save them on your local computer inside the same folder and please make sure the filenames are exactly how I listed on that table. Then load the file demo.html from your web browser.

It's a slightly modified version of what I shared here. Its behavior is fully consistent with any initial condition. I also added, for the sake of further education, a strategy to add new checkbox-label pairs to the page programmatically.

There are buttons on top of the page to:

  • Add a new checkbox
  • Reset the local storage
  • Reload the page

There's a lot to digest there if you are not familiar with developing web pages yet. Good luck!

  • Related