Skip to content

ally.js

JavaScript library to help modern web applications with accessibility concerns by making accessibility simpler

# ally.style.focusWithin

Polyfill the CSS Selectors Level 4 pseudo-class :focus-within

# Description

Since we cannot (easily) shim pseudo-classes, this function applies the class .ally-focus-within to all the elements that would match :focus-within. This method pierces the ShadowDOM and works with SVG.

This module allows the document to style :focus as follows:

body :focus {
  /* default styling in case JS broke */
  background: yellow;
}

body .ally-focus-within {
  /* styling parent elements of :focus */
  background: rgba(0, 0, 0, 0.3);
}

body .ally-focus-within:focus {
  /* styling :focus itself */
  background: red;
}

The :focus-within polyfill also works within the ShadowDOM, allowing the document styles to descend into the dark:

body >>> .ally-focus-within {
  /* styling parent elements of :focus */
  background: rgba(0, 0, 0, 0.3);
}
body >>> .ally-focus-within:focus {
  /* styling :focus itself */
  background: red;
}

/* older shadow-piercing-combinator notation */
body /deep/ .ally-focus-within {
  /* styling parent elements of :focus */
  background: rgba(0, 0, 0, 0.3);
}

# Usage

var handle = ally.style.focusWithin();

handle.disengage();

# Examples

# ally.style.focusWithin Example

ally.style.focusWithin Example on jsbin.com

play with ally.style.focusWithin Example on jsbin.com or open the document of ally.style.focusWithin Example

# Notes

In Firefox' about:config the option dom.webcomponents.enabled needs to be set to true to enable ShadowDOM support.

Firefox 34 does not expose ShadowRoot.host, coupled with document.activeElement pointing to the wrong element, we cannot find the first ShadowHost and can thus not apply focus-within properly. The ShadowRoot.host issue has been fixed in Firefox 37 (at the latest).

The focus-within class is added asynchronously in ShadowDOM, but synchronously for the document.

# Contributing