Tips for increasing the number of hide/show div toggles with unique classes

I am currently working on a project that involves toggling the visibility of different div classes. The toggle status is saved in local storage to ensure that the setting remains the same even after refreshing the page.

Recently, I attempted to create another toggle for a different class by simply copying and pasting the existing code and making necessary adjustments, but it didn't seem to work as expected.

If anyone has any suggestions or ideas on how to make this work seamlessly, please feel free to share them.

Fiddle: https://jsfiddle.net/snake93/s0rx4ube/9/

function save() {   
    var checkbox = document.getElementById("ck1");
    localStorage.setItem("ck1", JSON.stringify(checkbox.checked));  
}

function isChecked(isOn) {
    if (isOn === true) {
        $(".hideme").show();
    } else {
        $(".hideme").hide();
    }
}

//for loading
var checked = JSON.parse(localStorage.getItem("ck1"));
    document.getElementById("ck1").checked = checked;

console.log(checked);

$(document).ready(function(){
    isChecked(checked)
    $(".switch input").on("change", function(e) {
    const isOn = e.currentTarget.checked;
    console.log(isOn)
    isChecked(isOn);
  });
}); 
.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;
}
<!-- jQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<label class="switch">
<input type="checkbox" id="ck1" onchange="save()">
<span class="slider round hide-off"></span>
</label>
<br><br>

<div class="hideme">Please hide me, but bring me back later ;-)</div>

Answer №1

To increase dynamism, consider optimizing CSS selectors and adding an attribute with the same input ID to the divs you want to toggle visibility for.

HTML:

<label class="switch">
  <input type="checkbox" id="ck1">
  <span class="slider round hide-off"></span>
</label>
<br><br>

<label class="switch">
   <input type="checkbox" id="ck2">
   <span class="slider round hide-off"></span>
</label>
<br><br>

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

JAVASCRIPT

$(document).ready(function(){
    getLocalStatus()
    $(".switch input").on("change", function(e) {
       const element = e.currentTarget;
       saveStatus(element)
       setLabelVisibility(element.getAttribute('id'),element.checked);
    })
})

function getLocalStatus() {
    const checkboxes = $('input[type=checkbox]');
    checkboxes.each(function(index,checkbox){
        const checkboxId = checkbox.getAttribute('id')
        var currentStatus= localStorage.getItem(checkboxId)
        if (currentStatus == "true") {
            currentStatus = true;
        } else {
          currentStatus = false;
        }
        checkbox.checked = currentStatus;
        setLabelVisibility(checkboxId, currentStatus)
    })
}

function setLabelVisibility(id,status){
   const label = $("#label-" + id + "");
   if(status == false){
      label.hide();
      return;
   }
   label.show();
 }

 function saveStatus(e) {   
    localStorage.setItem(e.getAttribute('id'), e.checked)
 }

Answer №2

To enable the show/hide functionality for your DIVs, ensure that each one has a unique ID and pass these IDs into the function. This is just one method among many.

For distinguishing the element you wish to toggle from others, it must possess a distinct ID rather than relying on a class selector. The toggle function mandates two parameters: the invoking element and the ID of the element to be toggled. In the provided HTML snippet, 'this' references the specific checkbox being clicked. The '#div1' and '#div2' correspond to the IDs of the elements targeted for toggling.

The code related to local storage has been incorporated as well.

function toggle(p, c){
    if ($(p).prop("checked")){
        $(c).show();
    } else {
        $(c).hide();
    }

    localStorage.setItem($(p).attr("id"), JSON.stringify($(p).prop("checked")));

}
.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;
    display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="switch">
<input type="checkbox" id="ck1" onchange="toggle(this, '#div1')">
<span class="slider round hide-off"></span>
</label>

<label class="switch">
<input type="checkbox" id="ck2" onchange="toggle(this, '#div2')">
<span class="slider round hide-off"></span>
</label>
<br><br>

<div id="div1" class="hideme">Please hide me, but bring me back later ;-)</div>
<div id="div2" class="hideme">Please hide me, but bring me back later ;-)</div>

Answer №3

This alternative approach presents a solution that aligns with my preferences:

Adjust the input in the following manner:

<input type="checkbox" id="ck1" class="btn" data-toggle-id="#div1">

Subsequently, the javascript code (utilizing jquery) would be as follows:

$('.btn').on('change', function(){
    var $d = $($(this).attr('data-toggle-id'));
    if ($(this).prop("checked")){
        $d.show();
    }else{
    $d.hide();
  }
    
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Improper ordering using insert method within a forEach loop

I have an array containing objects that I need to import into a sqlite3 database using a forEach loop. The process is working correctly, but I noticed that the objects are not being imported in the same order as they appear in the database. This is my app ...

Warning: Be cautious of title array issues when implementing _document and page-specific next/head in Next.js

I've recently worked on setting up a basic _document file following the guidelines to add a Favicon and utilize Next/Head to define the title of each page (with plans to include more metadata). However, I encountered a warning message after making the ...

Do you prefer CSS icons or icon images?

I am currently managing a website that contains numerous icons, each of which is associated with a separate image. I have been contemplating the idea of combining all these icons into one image to improve loading speed. However, I am unsure if this would b ...

excess spillage occurring within the table's td elements

Is there a way to apply the overflow property to a cell within a table? http://jsfiddle.net/e8Bxj/ table { width:100px; height:100px; } td.content { overflow:auto; } <table> <tr> <td>hmm</td> </tr& ...

Having trouble finding an element in Python-Selenium and printing out the paragraph text?

I need assistance with web scraping Ark Invest's CIO commentary page from 2020 Q1 to 2021 Q4. The webpage can be found at this link, and I am using Selenium Webdriver for this task. My goal is to extract text from the page up until the paragraph that ...

Update the font URL in Bootstrap 5

I am looking to update the URL that Bootstrap uses to access fonts, as I want to host them on my server instead of relying on users to fetch them from Google with each page load. However, despite my efforts, I cannot locate the specific URLs mentioned when ...

Exploring how to set dropdown menu width for Angular2 mat-select options

Currently, I am using the angular2 mat-select control and facing an issue with the width and position of its dropdown list menu. By default, it is wider and overflows the element on both sides by a few pixels. I have not found any option for adjusting the ...

Validation errors are returned by express-validator duplicated

I am working on validating the request object using Express-Validator. Suppose I have two routes: a GET /users/:id route (fetchUserById) and a POST /users route (createUser). this.router = express.Router(); this.router.route('/').post(this.userR ...

Utilizing Python to extract text from a <td> element with XPath

Exploring the depths of XPath to extract data from an HTML document has been a fascinating challenge for me. Utilizing Python, I've successfully retrieved values such as webpage titles without any issues. However, when attempting to retrieve the text ...

Position the text to the left of the floating paragraph on the right

I am looking to align some text on the right side of the page with consistent starting positions. Each paragraph has two spans, one floated left and the other floated right. Here is an example with HTML and an image included for clarity. .card { ma ...

Examining an array to identify palindromes

Is there a way to loop through an array and check if each word is a palindrome, instead of manually passing an argument for each word? If a word is a palindrome, return the word; otherwise, return 0. var myArray = ['viicc', 'cecarar', ...

Using Node.js and Express to Handle Multiple Form Submissions

Currently, I am developing a webpage that contains two distinct forms with separate form actions. While I have managed to get one form working successfully, I am encountering difficulties in getting both forms to function simultaneously. In my code, I have ...

Exploring the benefits of utilizing express-session for authentication management

I am currently in the process of creating a basic login application using express 4 and express-session. When setting up my code as follows: app.use(session({ store: new MongoStore({ db: 'sess' }), secret: 'Ninja Turtle', cookie ...

Creating a function that uses setInterval to continuously update the input with a specific value

I am looking to use the setInterval function to continuously update the value of #test1. Additionally, I want the value of #test1 to be cleared and reset to 1 second after the user clicks a button. Example output can be found here: http://jsfiddle.net/eK ...

The current status of Dropzone.js is in a pending state, preventing the upload of any

I have integrated Multer in the back-end for file upload handling and Dropzone.js in the front-end. Testing my back-end code with Postman works perfectly, but when using Dropzone, the status remains pending and the file does not get uploaded. After waiting ...

Button does not display jQuery tooltip

I'm currently experimenting with the jQuery UI Tooltip plugin using jQuery v1.7.2 and jQuery UI v1.10.4 The issue I'm encountering can be seen in this basic example I've set up here: http://jsfiddle.net/bCN4X/1/ My goal is to have the tabl ...

Unravel the audio and start with the introductory segment before seamlessly transitioning into the

My music track includes an intro (I), a looped section (L), and an ending (E). I'm looking to prevent the ending from playing, so the audio file would be I + L + E, but only I + L should be heard on playback. I managed to achieve this by splitting th ...

Encountering an error that states "this.push is not a function" when trying to select the 2nd or 3rd option

My goal is to extract elements from a drop-down menu and populate a list box based on the selection. The selected value from one list box should then be transferred to another list box, specifically from Available to Selected. However, while selecting Deve ...

A structured HTML table featuring a secure header and stable left-hand columns, complete with knockout controls embedded in both the header and first

I'm facing a challenge with a customizable HTML table: Each row has a checkbox (knockout bound) to allow the user to determine if it should be included or not. The header columns also have checkboxes (knockout bound) to indicate if a particular ...

Is it possible to bypass the standard syntax and manipulate geometry buffers directly in three.js in order to achieve improved performance?

Embarking on a creative journey into the realm of geometry generation and manipulation, I am eager to explore intricate and large-scale projects. While I am familiar with the conventional methods of achieving this, as demonstrated in the informative respon ...