I have a navbar in with I am changing the width when the checkbox is clicked. When the checkbox is clicked, I want the navbar to smoothly transit to the larger width. It seems to be working only the first time on the snippet.
Here is the code I have:
function change() {
var nav = document.getElementById("navbar");
var checkBox = document.getElementById("checkbox");
if (checkBox.checked == true) {
nav.style.width = "300px";
} else {
nav.style.width = "fit-content";
}
}
nav {
display: flex;
flex-direction: column;
justify-content: space-between;
width: 100px;
height: 100%;
transition: 0.3s;
box-shadow: rgba(136, 165, 191, 0.26) 4px 2px 10px 0px, rgba(255, 255, 255, 0.8) -4px -2px 16px 0px;
}
nav input {
margin: 10px;
position: absolute;
width: 50px;
height: 50px;
opacity: 0;
cursor: pointer;
}
<nav id="navbar">
<input onclick="change()" type="checkbox" name="" id="checkbox">
<p>Home</p>
</nav>
A transition only works on numeric values, so you need to change the width in the else-case accordingly, for example to 50px.
function change(){
var nav = document.getElementById("navbar");
var checkBox = document.getElementById("checkbox");
if(checkBox.checked == true){
nav.style.width = "300px";
} else{
nav.style.width = "50px";
}
}
nav{
display: flex;
flex-direction: column;
justify-content: space-between;
width:100px;
height: 100%;
transition: 0.3s;
box-shadow: rgba(136, 165, 191, 0.26) 4px 2px 10px 0px, rgba(255, 255, 255, 0.8) -4px -2px 16px 0px;
}
nav input{
margin: 10px;
position: absolute;
width: 50px;
height: 50px;
opacity: 0;
cursor: pointer;
}
<nav id="navbar">
<input onclick="change()" type="checkbox" name="" id="checkbox">
<p>Home</p>
</nav>