What is the best way to synchronize the checking and unchecking of two separate checkboxes located in different divs?

I recently implemented two checkboxes to switch between dark mode and light mode. One checkbox pertains to the mobile navigation, while the other one is related to the desktop navigation.

When the screen width reaches 800px, the visibility of the checkboxes changes – the mobile checkbox is hidden with 'display:none' property while the desktop checkbox becomes visible with 'display:block', and vice versa for widths below 800px.

The problem arises when I switch from the desktop view with dark mode enabled to the mobile view where the mobile checkbox remains unchecked. Even when I try to check it, the light mode works but then the desktop checkbox reflects the opposite state.

Currently, my focus is on updating both checkboxes to be marked as ':checked' upon clicking either input element.

I suspect that my issue may stem from the impossibility of marking a checkbox as checked when it's rendered invisible with 'display:none' and not present in the Document Object Model (DOM).

Access the Codepen project here.

$(document).ready(function() {

  $('input[type="checkbox"]').on('click', () => {

    $('body').toggleClass('darkMode');

    $('mobile-checkbox').is(':checked');
    $('desktop-checkbox').is(':checked');

  });

});
.darkMode {
  background-color: black;
}

.mobile {
  display: inline-block;
  box-shadow: 5px 5px 5px blue;
}

.desktop {
  display: none;
  box-shadow: 5px 5px 5px green;
}

@media (min-width:800px) {
  .mobile {
    display: none;
  }
  .desktop {
    display: inline-block;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <div class="mobile">
    <input class="mobile-checkbox" type="checkbox">
  </div>

  <div class="desktop">
    <input class="desktop-checkbox" type="checkbox">
  </div>
</body>

Answer №1

To synchronize the checked state of two checkboxes, simply set the prop checked to match the changed checkbox. I included a console log for visual confirmation of the change. Adding a common class to both checkboxes can simplify the selection process.

$(document).ready(() => {
  let $body = $(document.body);
  let $viewSelectors = $('.view-selector').on('click', e => {
    $body.toggleClass('darkMode');
    $viewSelectors.prop('checked', e.target.checked);
    
    console.log($viewSelectors.map((index, it) => it.checked).get());
  });
});
.darkMode {
  background-color: black;
}

.mobile {
  display: inline-block;
  box-shadow: 5px 5px 5px blue;
}

.desktop {
  display: none;
  box-shadow: 5px 5px 5px green;
}

@media (min-width:800px) {
  .mobile {
    display: none;
  }
  .desktop {
    display: inline-block;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mobile">
  <input class="mobile-checkbox view-selector" type="checkbox">
</div>

<div class="desktop">
  <input class="desktop-checkbox view-selector" type="checkbox">
</div>

Answer №2

Although the code may not be perfect, here is a straightforward solution:

$( document ).ready(function() {
  var $checkboxes = $('input[type="checkbox"]');
    $checkboxes.on('change', function(){
      if(this.checked){
        $('body').addClass('darkMode');
        $checkboxes.prop('checked', true);
      }
      else{
        $('body').removeClass('darkMode');
        $checkboxes.prop('checked', false);
      }
    });
});

This script checks the state of a checkbox on change and updates all checkboxes accordingly.

Avoid using arrow functions in this instance to utilize the 'this' keyword effectively.

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

Vue JS: Breathing Life into Your Elements

Incorporating Vue-Router and Vuex, I have successfully implemented a Users Profile Component that fetches user information by extracting the username parameter from a router-link. For example, <router-link :to="{name: 'user', params: { usernam ...

Customize the color of a Bootstrap btn-group

Is there a way to modify the background color of the active or selected button within a button group? <div class="btn-group" role="group" aria-label="Basic radio toggle button group"> <input type="radio" c ...

I have a task of verifying nine numbers that are similar in all digits

Can someone guide me on generating a pattern in PHP to ensure that these repetitive numbers do not occur in my text input? 000000000 111111111 222222222 333333333 444444444 555555555 666666666 777777777 888888888 999999999 ...

Navigation Bar with Dropdown Feature not Functioning Properly in CSS and HTML

I recently developed a website using CSS, HTML, and PHP. The main focus of my work has been on improving the navigation bar in the header section. However, after several hours of tweaking, I finally achieved the desired look for the navigation bar. Unfortu ...

Having trouble getting the focus-within CSS pseudo-class to work with an HTML label

I'm attempting to create a dropdown menu with checkboxes inside the dropdown area. Below is the code snippet I am using: .search-box { color: black; width: 450px; } .search-box .fake-tb { display: flex; flex-wrap: nowrap; background: #f ...

Showing a Remote Image on the Screen

I have a 16x16 grid of thumbnail images and I'm trying to implement a feature where clicking on an image displays the full-sized version with a dimmed background. The full-sized image should appear to float above the background. I don't want to ...

OBJ Raycasting in Three.js

Greetings! I encountered an issue while working with three.js in my project. Specifically, I was trying to select a custom mesh that I loaded from an OBJ file. To troubleshoot, I set up a simple raycaster, a cube, and my custom model (which is also a cube ...

How to retrieve multiple person or group values in SharePoint using JavaScript

Names from my SharePoint list are stored with the field names 'People' and 'Responsible', added using a peoplepicker. These fields are of type 'person or group' in SharePoint. In my Service file, I have the following code: ...

How can I create a notification popup triggered by a button click with Ajax and Javascript?

I'm in the process of developing a website that involves notifications, but I am unsure how to display them when a button is pressed. For example, clicking "Show Weather" should trigger a notification to appear in the bottom corner of the page. https ...

Creating a Dynamic System for Converting Numeric Digits to Alphabetical Grades

Utilizing the code provided below, you can calculate a user's grade point average ranging from A+ to E-. Is there a way, within the following fiddle, to not only display the GPA but also convert it into a corresponding letter grade from A+ to E-? Curr ...

Transforming brand logos through hover on image maps

Despite finding numerous posts addressing this issue, I am still encountering problems with my code: <div id="product_tabs_description_tabbed_contents" style="display: block;"><img style="margin-left: -10px; opacity: 1 !important;" src="{{media u ...

The parameter type 'NextHandleFunction' does not match the expected type 'PathParams' in the argument

After successfully setting up TypeScript with a basic Express server, I've encountered an issue. import bodyParser from 'body-parser'; import express, { Express } from 'express'; const app: Express = express(); app.use(bodyParser ...

Angular monitoring problem

Today marks my first attempt at utilizing Angular's watch function, but I'm having trouble getting it to function properly. Within my codebase, there exists a service named apiService, housing a variable called myFile. By injecting this service i ...

Sophisticated layering of partials and templates

I am facing a challenge in handling intricate nesting of templates (also known as partials) within an AngularJS application. To illustrate my predicament, I have created an image: As depicted, this application has the potential to become quite complex wi ...

Feeling grateful: Enable scroll functionality for a log widget

I am currently utilizing the Blessed library to create a dashboard within the terminal. My issue lies in making the log widget scrollable. Despite implementing the code below, I am unable to scroll using my mouse wheel or by dragging the scrollbar: var l ...

Triggering a notification from the user's end in response to server feedback

I am currently utilizing express.js on the server-side and plain JavaScript on the client-side. In the sign-up route, I aim to add a user only if they have not already signed up. If the user has already signed up, I want to display an alert message saying ...

The issue with routerLink not functioning properly in e2e testing with Protractor within an Angular 2 environment

I have implemented an angular2 routerLink that allows users to navigate to the editComponent by passing the userId as a parameter. <a [routerLink]="['/edit',user._id]" (click)="returnUser(user._id)" id="redirect" class="btn" name="user-{{ ...

Calculate the sum of each row within a grouped object

My task is to sum up the values of minutes and seconds_left, then group them by id_project. 0: {id_project: 2, minutes: 12, seconds_left: NaN} 1: {id_project: 3, minutes: 15, seconds_left: 11} 2: {id_project: 4, minutes: 0, seconds_left: 11} 3: {id_projec ...

Adjust website layout for screens less than 320px in width

Struggling to complete my project and having trouble figuring out how to scale my website for screens smaller than 320px, even though they are rare. I admire the solution used by Apple where the website freezes and scales down while maintaining its origin ...

Issue with nested tabs functionality within a pill tab panel in Bootstrap not functioning as expected

I'm facing a challenge with integrating tabs into a vertical pill tab panel in Bootstrap 4. Below is a brief code snippet: <html> <head> <link href="bootstrap.min.css" rel="stylesheet"> </head> <body> <script ...