I want to make a button that would move, first to the right, then to the left when pressed again.
After a lot of searching, I've been able to make it, but I have to declare it two times. Like, the code won't accept the CSS
version.
Here's my code :
HTML
<div id="light"><div id="button"></div></div>
CSS
padding: 10px;
#light {
position: relative;
width: 40px;
margin: auto;
background-color: black;
z-index: 10;
margin-top: 420px;
height: 20px;
border-radius: 40px;
}
#button {
width: 16px;
background-color: cornflowerblue;
height: 16px;
border-radius: 40px;
position: relative;
top: 2px;
left: 4px;
cursor: pointer;
transition: 0.5s;
}
JS
var button = document.getElementById("button");
button.style.left = "4px";
button.onclick = function() {
if (button.style.left === "4px") {
button.style.left = "20px";
} else {
button.style.left = "4px";
}
}
If I delete the button.style.left ="4px"
declaration from the JS, it wouldn't works because if I do console.log(button.style.left)
, the result would be nothing.
And that's the thing I don't quite understand there.