Works in the latest version of IE, Chrome, Firefox, and Safari.
This toggle switch can be used to turn things into an “on” or “off” state (for example, through HTTP requests via AJAX), and the state is represented by the toggle’s CSS.
The toggle is made up of two components:
The “toggle” (the container for the whole thing):
This toggle gets the badass class name of, you guessed it,
.toggle. It can also receive the
The next component is the “switch” (the little round thing that moves back and forth):
Principle of function
The only thing that changes when you click the toggle is its padding!
What this “on” class does is set the
padding-left of the toggle () so that the switch appears to move to the side.
All we do after that is add some nice CSS3 transitions to the
padding by saying something like
transition: 400ms cubic-bezier(0, 0, 0, 1);, and we have a working switch.
Don’t SASS me
In its simplest form
For the slow people like me, here is a bare-bones version using regular ol’
onclick and CSS (and some bad practices).
Well that’s that: a simple CSS selector switch (all it needs is a click handler). You could also make this an AngularJS directive called, say,
<toggle></toggle>, and add the click handler inside the directive.
Key points: The switch moves by just changing the padding, and you can add a transition to make it all smooth-like.