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>