Making toggle switch in Smooth UI is pretty easy. You just need to use a div with switch as class name. This will automatically convert the div into a switch.
<div class="switch"></div>
Under the hood, Switch uses HTML's Checkbox.
The above piece of code will create a switch in UI.
Result
Switch Off
Switch On
Attributes
In order to use this switch practically, here are some attrbutes you will need to use.
data-checked (Optional): 'on' | 'off'
data-checked attribute is equivalent to checked attribute in HTML Checkbox. Hence, data-checked informs SmoothUI to make the switch on by default.
Example
<div class="switch" data-checked="on"></div>
<div class="switch" data-checked="off"></div>
data-name (optional)
data-name is needed to use the switch as a form field in HTML, ie when the form is submitted, option of the switch is sent as the value of the key in its value.
On form submission it will send data as saveme: on | off
Example Submission (GET)
data-required (optional)
This makes turning on the switch mandatory if it is not. It is equivalent to required in other HTML Form fields. Hence, form will not be submitted until the switch is on. However, it will not prompt any visual error to user, hence you need to handle such exceptions manually.
onclick (optional)
This event is useful when using Switch outside traditional <form> or when handling exception as mentioned above.
Handling Switch State
As mentioned above, you can invoke a function with onclick attribute. Ofcourse, you can use JavaScript event listeners too, but it is tricky to maintain the switch state manually, hence instead Smooth UI provides with a JavaScript method to get current Switch State.
Here is how to use it
Whenever listening to click event of switch, you can pass JavaScript's event variable to the function block and use it to fetch current state of switch. To get current value of switch you have to use smoothUI.switchState method and pass the event variable to it. If this function returns true that means that the switch is on else false.
Example
Here is another example which uses Event Listeners instead.
If you are wondering what is $1 method used in above code, it is the Shorthand function that comes with SmoothUI that runs JavaScript's document.querySelector
Getting Switch State without event
You can get Switch Current without event variable, instead you can use a selector to select the switch and pass it to smoothUI.switchStateBySelector method. If it returns true that means the switch is on else false.