Uncategorised

How to Make a Toggle Work

As the name suggests a toggle is a switch that can be turned on or off. We see toggles everywhere in our everyday lives — switching between screens when video chatting with two friends at the same time, or flipping between maps and streams on the live map app we use while hiking. Toggles have a place in many interfaces but, as with all things, they need to be used carefully. They can be confusing if applied too broadly and they are often made inaccessible by designers and developers who don’t know much about accessibility. So let’s talk about how to make toggles really work.

Toggles are a great choice when you need a control that has an immediate effect without needing to click Save or any other input. They are not however the best solution for all interfaces and in some cases other controls such as checkboxes or radio buttons might be better.

A Toggle can be configured either by hardcoding in the code, using a preprocessor’s #ifdef feature (where available) or, more commonly, via a CSS rule set. Each of these approaches has its own benefits and drawbacks. Hardcoded configuration tends to be the most reliable and easiest to understand but it is also a bit more restrictive in that you cannot change the toggle state unless you re-deploy the associated code. For this reason we generally only use this type of toggle with flags that need to remain constant.

The other main advantage of a Toggle is the ability to configure its behaviour dynamically via CSS. This can be very useful for Feature Flags where we want to make a toggle conditional based upon the user’s context or behaviour, and where we might want to experiment with different combinations of toggle states.

One example of this would be an Ops Toggle which could be configured to display a warning when cookies are enabled or not to warn that a cookie is being created. This is something that can be difficult to do with a standard button as the default configuration is always “on”.

There are some situations where a Toggle might be more suitable than a standard button>, for example if you need to indicate the current state in text rather than in an icon or when the interface requires a vertical layout and there is no room left to display the toggle label. Adrian Roselli has a good article on when to pick a toggle and when a checkbox or radio button might be more appropriate. He also has an excellent demo of a small HTML + CSS only implementation of an accessible toggle that you can copy and paste into your own projects.