A Missing Pattern: Dynamic Attributes

A Common Pattern

When building user interfaces on the web, there's a class of problem that is extremely common which goes something along the lines of:

When a user interacts with Element (usually clicks), update a property (usually class) on the Element (or some other element), based on some simple logic.

For example, to build a simple custom dropdown, you might specify...

When a user clicks on the dropdown button, toggle the .visible class on the drawer

For a left sidebar or tab navigation, you might specify...

When a user clicks on a menu item, set the class to active, and remove the active class from all other menu items

For an accordion...

When a user clicks on a drawer title, toggle `.active` on the content div, and remove `.active` on the other content divs.

Not Just Classes

While the most common use case is to toggle a class, there are other common patterns:

  • Toggle the text in this span when the value of this form input changes.

  • Toggle the value of this hidden form input when the value of this other form input changes.

The Options

Vanilla JS

Hyperscript

Alpine

Web Component

React

Stimulus

Mini Js

Last updated