So I have set up a light and dark theme using variables in css and I want my toggle to change the data theme from "light" to "dark" – how do I do this?
JS
$(document).ready("#toggle_checkbox").click(function() {
$('body').attr('data-theme', $('body').attr('data-theme') == 'light' ? 'dark' : 'light')
});
HTML
<body data-theme="light">
<input type="checkbox" id="toggle_checkbox">
<label for="toggle_checkbox" onclick="">
<div id="star">
<div class="star" id="star-1"></div>
</div>
</label>
</body>
Could someone help me understand where I’m going wrong?
I’ve tried applying the above JS but the click is applied to the whole page (I can click anywhere and it will change the theme) instead of clicking on the input itself.
2
Answers
In this corrected version, I’ve made sure that the click event is bound to the #toggle_checkbox element within the $(document).ready() function. This ensures that the event binding only occurs after the page has finished loading.
When the checkbox is clicked, the code uses the .attr() method to toggle the value of the data-theme attribute between ‘light’ and ‘dark’. The ternary operator (… ? … : …) is used to achieve this toggle behavior.
This would work and be shorter
If you wanted shades of gray, you could do