Is a simple example of a toggle button.
You need to start with the input button and then get the state of this
1 | var x = document.getElementById("switch").checked; |
Then add the type and id and style.
You can remove the text-indent: -9999px; and Toggle button if you don’t want to see text to this toggle button.
Let’s see the full source code and how is working.
The part after hr tag with button and paragraph tag id=output is just for tested the toggle button.
You can make an HTML file and put this source code to test it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title of the document</title> <style>input[type=checkbox]{ height: 0; width: 0; visibility: hidden; } label { cursor: pointer; text-indent: -9999px; width: 200px; height: 100px; background: red; display: block; border-radius: 100px; position: relative; } label:after { content: ''; position: absolute; top: 5px; left: 5px; width: 90px; height: 90px; background: #fff; border-radius: 90px; transition: 0.3s; } input:checked + label { background: #0f0; } input:checked + label:after { left: calc(100% - 5px); transform: translateX(-100%); background: 0f0; } label:active:after { width: 130px; } // centering body { display: flex; justify-content: center; align-items: center; height: 100vh; }</style> </head> <body> <input type="checkbox" id="switch" /><label for="switch">Toggle button</label> <hr> <button onclick="myFunction()">Try it</button> <p id="output"></p> <script> // check the input button function myFunction() { var x = document.getElementById("switch").checked; document.getElementById("output").innerHTML = x; } </script> </body> </html> |