简体   繁体   中英

How to make a toggle button with vanilla javascript and css without any html

I tried to find a solution and people always gave either solutions with html or jQuery or what have you.

So I made one and thought it might be helpful for others.

 let defaultSetting = "off" const toggleButton = document.createElement('toggleButton'); toggleButton.onclick = function(){toggleSwitchTransformFunction()}; document.body.appendChild(toggleButton); const toggleSwitchCircle = document.createElement('toggleSwitchCircle'); toggleButton.appendChild(toggleSwitchCircle); function toggleSwitchTransformFunction() { if(defaultSetting == "off"){ defaultSetting = "on" toggleSwitchCircle.style.transform = "translateX(100%)" toggleButton.style.background = "black" // execute code when ON } else if(defaultSetting == "on"){ defaultSetting = "off" toggleSwitchCircle.style.transform = "translateX(0%)" toggleButton.style.background = "white" // execute code when OFF } }
 toggleButton{ width: 84px; min-width: 84px; display: block; padding: 4px; border: 1px black solid; border-radius: 60px; transition: 0.5s; } toggleSwitchCircle { display: block; width: 40px; height: 40px; border: 1px black solid; background-color: white; border-radius: 50%; transition: 0.5s; }

You can also easily do a pure CSS toggle by using an input and label.

https://codepen.io/seanstopnik/pen/f0d8ba0f9b0a317c324ee16f49ba945c

 document.body.innerHTML = document.body.innerHTML + "<div class=\"toggle\"><input id=\"toggle1\" class=\"toggle__checkbox\" type=\"checkbox\"><label for=\"toggle1\" class=\"toggle__label\"></label></div>";
 /* For demo only */ body { font-family: sans-serif; background: #2d4a65; padding: 60px; } /* Toggle */.toggle { position: relative; width: 80px; height: 40px; border-radius: 20px; box-shadow: inset 0 2px 1px rgba(0, 0, 0, 0.1); background-color: #1e3648; overflow: hidden; }.toggle__checkbox { position: absolute; left: -9999px; }.toggle__label { position: relative; display: inline-block; top: 4px; left: 4px; width: 32px; height: 32px; border-radius: 16px; background-color: #fff; transition: all 0.25s ease-in-out; cursor: pointer; }.toggle__label:before, .toggle__label:after { position: absolute; top: 0; color: #fff; font-size: 13px; font-weight: bold; text-transform: uppercase; line-height: 32px; transition: all 0.15s ease-in-out; }.toggle__label:before { left: -30px; content: "on"; opacity: 0; }.toggle__label:after { left: 37px; content: "off"; opacity: 1; }.toggle__checkbox:checked ~.toggle__label { left: 44px; }.toggle__checkbox:checked ~.toggle__label:before { opacity: 1; }.toggle__checkbox:checked ~.toggle__label:after { opacity: 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM