Reputation: 87
I'm currently trying to develop a darkmode feature for my website using jQuery's toggle method. At this point when the toggle is clicked the body colour changes, however, I wish for the header background colour to also change. How can I accomplish this?
current code base
$(document).ready(function(){
$('#checkbox').click(function(){
var element = document.body;
element.classList.toggle("dark");
});
});
</script>
As seen you can use document.body
to change the content of the body. I wish to achieve the same affect but for the header(and subsequently other elements)
P.S Jquery is mandatory
Upvotes: 1
Views: 402
Reputation: 382
This is done using jquery:-
$(document).ready(function() {
$('#checkbox').click(function() {
var element = document.body;
element.classList.toggle("dark");
});
});
* {
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
transition: background 0.2s linear;
}
body.dark {
background-color: #292c35;
}
.checkbox {
opacity: 0;
position: absolute;
}
.label {
width: 50px;
height: 26px;
background-color: #111;
display: flex;
border-radius: 50px;
align-items: center;
justify-content: space-between;
padding: 5px;
position: relative;
transform: scale(1.5);
}
.ball {
width: 20px;
height: 20px;
background-color: white;
position: absolute;
top: 2px;
left: 2px;
border-radius: 50%;
transition: transform 0.2s linear;
}
/* target the elemenent after the label*/
.checkbox:checked+.label .ball {
transform: translateX(24px);
}
.fa-moon {
color: pink;
}
.fa-sun {
color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<div>
<input type="checkbox" class="checkbox" id="checkbox">
<label for="checkbox" class="label">
<i class="fas fa-moon"></i>
<i class='fas fa-sun'></i>
<div class='ball'>
</label>
</div>
Upvotes: 1