I want to be able to listen to CSS selector state changes on elements, similarly to matchMedia
Submitted by Guylian Cox
Permalink https://webwewant.fyi/wants/67ee170f-3be8-4bea-a24d-56075677e087/
This idea is currently being discussed.
I want to be able to listen for changes in whether a CSS selector matches a given element, in much the same way that matchMedia lets me react to media query changes.
The Element.matches(selector) method lets me test whether an element matches a CSS selector at a single point in time, but it gives me no way to be notified when the match state changes. For instance, I cannot be told when an input transitions into or out of :placeholder-shown, :user-invalid, or :focus-visible without polling or attaching workaround event listeners. This limitation is particularly painful in scenarios where:
- Float label implementations rely on
:placeholder-shownto decide whether to animate a label, but programmatic changes toHTMLInputElement.valuedo not fire any DOM events, so the match state can drift undetected. - User-invalid-driven error messages need to appear and disappear as
:user-invalidchanges, but there is no reliable event for that. - Focus-visible-based UI states (e.g., ripple effects in Material Design) require userland polyfills because
:focus-visibleproduces no corresponding JavaScript event.
The API I am imagining is analogous to matchMedia:
const observer = element.matchSelector(':placeholder-shown');
observer.addEventListener('change', (event) => {
console.log('placeholder shown:', event.matches);
});A more ambitious alternative — which would cover all of the above and more — is a CSS.observe() primitive that notifies script whenever any element's match state changes for an observed selector:
CSS.observe('input:placeholder-shown', (selector, records) => {
// records: [{ target: inputEl, matches: true/false }]
});Either form would dramatically reduce the need for polling loops, multiple MutationObservers, or fragile event-handler combinations just to react to CSS pseudo-class state changes.
- Votes
- 0
What are votes for and how are they tallied?