How TO — Toggle Switch
Learn how to create a «toggle switch» (on/off button) with CSS.
How To Create a Toggle Switch
Step 1) Add HTML:
Example
Step 2) Add CSS:
Example
/* The switch — the box around the slider */
.switch position: relative;
display: inline-block;
width: 60px;
height: 34px;
>
/* Hide default HTML checkbox */
.switch input opacity: 0;
width: 0;
height: 0;
>
/* The slider */
.slider position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
>
.slider:before position: absolute;
content: «»;
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
>
input:checked + .slider background-color: #2196F3;
>
input:focus + .slider box-shadow: 0 0 1px #2196F3;
>
input:checked + .slider:before -webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
>
/* Rounded sliders */
.slider.round border-radius: 34px;
>
.slider.round:before border-radius: 50%;
>
I am trying to make a simple toggle button in javascript
Why are you passing the button if you’re going to look it up?
Also, since you know the possible values, you only need to check if it’s OFF, otherwise, you know it’s ON.
// Toggles the passed button from OFF to ON and vice-versa. function toggle(button) < if (button.value == "OFF") < button.value = "ON"; >else < button.value = "OFF"; >>
If you wanna get fancy and save a couple of bytes you can use the ternary operator:
function toggle(b)
answered Jun 15, 2010 at 18:08
68.5k 30 30 gold badges 171 171 silver badges 213 213 bronze badges
Both of your if statements are getting executed one after each other, as you change the value and then immediately read it again and change it back:
function toggle(button) < if(document.getElementById("1").value=="OFF")< document.getElementById("1").value="ON";>else if(document.getElementById("1").value=="ON") < document.getElementById("1").value="OFF";>>
Adding the else in there should stop this happening.
answered Jun 15, 2010 at 18:05
27k 8 8 gold badges 58 58 silver badges 65 65 bronze badges
Also, if you know that the value can only be «ON» or «OFF», you can omit the second if completely and simply use else .
Jun 15, 2010 at 18:06
Another method to do this is:
var button = document.querySelector("button"); var body = document.querySelector("body"); var isOrange = true; button.addEventListener("click", function() < if(isOrange) < body.style.background = "orange"; >else < body.style.background = "none"; >isOrange = !isOrange; >);
In the JavaScript file.
NOTE! Another way is applying a class to the element that we want to change.
The CSS file must have the class with the format we want:
.orange
By last in our js file we only need to make the application of the class:
var button = document.querySelector("button"); button.addEventListener("click", function() < document.body.classList.toggle("orange"); >);
