Toggle without JavaScript and native input field #7996
voidmain
started this conversation in
Show and tell
Replies: 1 comment
-
Nice work! I tried it out in Tailwind Play but I set the input field to hidden. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I was originally using the Tailwind UI toggle's but I realized that there was a simpler way to create a toggle without JavaScript and using native input fields. It's pretty slick so I thought I would share. My solution positions the checkbox, pin, and rail as absolutely positioned elements inside a
<label>
.I removed the
aria
attributes and the<span>
for screen-readers, but those could easily be added back in. The key is that this requires that all the element be inside the<label>
so that it can be used to check the checkbox since that element isn't always clickable. Plus, it usespeer
to apply the changes when the checkbox is checked.Getting the focus to work took a bit of work but I found that making the checkbox itself the full width and height of the toggle and then styling it down to nothing (borders, etc) worked well and didn't get in the way of the other elements due to document order z-index stacking but it did allow the ring to expand around the toggle.
Feel free to give it a shot and hit me up with any questions.
Beta Was this translation helpful? Give feedback.
All reactions