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 Shadow DOM, 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

🔗Example: ally.style.focusWithin Example

ally.style.focusWithin Example on jsbin.com

play with the example on jsbin.com or open the source document

🔗Notes

NOTE: In Firefox the setting dom.webcomponents.enabled needs to be set to true to enable ShadowDOM support.
NOTE: 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).
NOTE: The focus-within class is added asynchronously in Shadow DOM, but synchronously for the document.

🔗Related resources

🔗Contributing