The switch component should be used to represent boolean options which expect either a true
or false
state.
From a UX perspective, this should only be used for options which areupdated instantaneously. If the data is only updated following the user's click of a "save" button, the checkbox would be a more appropriate component to use. (Why?)
Behind the scenes, the switch is essentially just a standard checkbox element. By simply adding a checked
attribute to the c-switch__checkbox
element, the switch will be on by default.
This switch component has multiple states available. These can also be combined with any combination of modifiers, unless stated otherwise.
Most states are also activated when a parent component has the same state applied. For example, if a fieldset
element is disabled or has an is-disabled
class, this will also activate the disabled state for all its child components with states available.
This behaviour can be disabled by adding a --disable-state-inheritance
modifier class to the element inheriting the state (For example, for c-button
, the class would be c-button--disable-state-inheritance
).
This component has methods which allow you to programatically trigger actions. You can trigger these using the evo()
selector.
See JavaScript API for more information and a list of shared, global methods.
Toggles the switch
evo('.js-my-switch').checkbox('toggle');
// Toggles a switch only if the input element within it matches the selector in the 'input' option
evo('.js-my-switch').checkbox('toggle', {
input: '[name="switch-name"]'
});
This component has bespoke events which trigger automatically on certain actions. You can hook into these using event listeners to run your own custom code.
Typically, most events are fired from the block level class (eg:- c-tabs
), however some may fire from element level classes (eg:- c-tabs__item
). In practice, this usually doesn't matter as these element level events will bubble upwards and trigger any listeners on the block element. When this happens, you can get a reference to the element via the target
property of the event object.
Name | Description |
---|---|
|
Fires when the switch is turned on. |
|
Fires when the switch is turned off. |
Example code snippet showing how you can set up an event listener.
const element = document.querySelector('.c-my-component');
element.addEventListener('eventName', (e) => {
console.log('my event has fired');
// Access event details object, if it exists
console.log(e.details);
// Access the element the event was fired from
console.log(e.target);
});
You can theme the switch component to make it fit your brand. For more information on theming EvoToolkit, please see Configuring EvoToolkit.
Below is a list of theme variables and their default values.
Theme Variables | Default |
---|---|
$component-switch-background-color |
very-light |
$component-switch-border-color |
light |
$component-switch-button-color |
white |
$component-switch-focus-color |
primary |