Skip to content

Progressively enhanced toggle button

On the bbb.org search, we have a toggle for showing only BBB accredited businesses. When the toggle button is clicked, the search results automatically reload. I was working on rebuilding the HTML/CSS for this component, and wanted to consider an experience for when JavaScript failed to load.

The first idea that came to mind was using a checkbox. This could be toggled on and off regardless of whether JS was available, but would need an extra submit button when JS was not available in order to submit the form. This approach felt too much like two separate solutions to the same problem to me, so it was back to the drawing board.

It was in the comments of Adrian's post that I got the idea that I ended up using. By adding a name and value to the button, I could tell on the server whether the button was currently checked or not, and perform the same logic that I was doing on the client when JavaScript was available.

<!-- checked -->
<button class="toggle-button" role="switch" aria-checked="true" name="toggle" value="on">
  Show all businesses
</button>
<!-- unchecked -->
<button class="toggle-button" role="switch" aria-checked="false" name="toggle" value="">
  Show all businesses
</button>

On server load, the aria-checked value will be set to communicate the current state of the toggle button. The value attribute will be set to on or '' so that when the form is submitted, I can interpret the value on the server-side to perform my filtering there.

Check out the full example that I wrote on Codepen.

The main markup that I used was heavily influenced by Inclusive Components and Adrian Roselli.