Surface JavaScript APIs for selector match changes

This post is a follow up to the CSS.Next discussion at the  Extensible
Web Summit.

Element#matches can test the current state of a selector against an
element, but theres no unified way to know when a selector will be
matched or unmatched in the future.

Detecting selector changes are typically used by CSS polyfills. And
even application code usually needs to enable or disable behavior
after as the page dynamically changes. Typically developers only check
selectors once on DOMContentLoaded which is error prone.


One possible API might fit into Tab's old EventStream idea
(http://www.xanthir.com/b4PV0).

    el.watchMatches('.foo').then(function(matches) {
      if (matches)
        console.log(el, 'now matches .foo');
      else
        console.log(el, 'no longer matches .foo');
    });


Although, I think I would find a more MutationObserver like API more
useful. Since it could pick up new elements added to the tree that
match the selector.

    var observer = new SelectorObserver(function(record) {
      console.log(record.target, 'now matches', record.selector);
    });
    observer.observe(document, {selector: '.foo'});


MutationObservers do provide low level plumbing for node and attribute
changes. Then there are UI events like focus and change. But theres a
set of current pseudo classes that depend on element on property state
and do not have reliable change events, like :checked, :indeterminate,
:enabled and :disabled. Trying to implement this efficiently in JS
gets tricky as well. Other hacks piggy back on the animationstart
event to attempt to leverage the efficiently of the browsers css
matcher (http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/).


I feel like exposing some sort of API like this would help explain the
magic behind CSS rule matching and style application today.

--
Josh Peek
Developer at GitHub

Received on Tuesday, 8 April 2014 01:04:51 UTC