focus-source

This module makes it possible to style the :focus state of elements differently if the focus was caused by a keyboard.

It does this by maintaining a data-focus-source attribute on the <body> element.

For example:

<body data-focus-source="keyboard"></body>

A corresponding css rule exists in base.css that looks as follows:

[data-focus-source='keyboard'] *:focus {
  outline: 2px solid var(--colorGreenApron);
}

Now focus styles will only be applied if the :focus state was caused by the keyboard.

Why would you want this?

In short, for better accessibility.

This module has been adapted from WICG Modality mainly in order to be more npm friendly. An explantion of the rationale of the project can be found in that project's readme

How to use it

Step #1: Install the pattern library into your project:

npm install @cxeweb/pattern-library

Step #2: Import the function and call it from your module:

import { focusSource } from '@cxeweb/pattern-library';

// only call this *once*
// the only requirement is that `document.body` exists
focusSource();

Step #3: Make sure you're using the base css in your project.

That's it!

(optional) Modify styles for keyboard focused elements

By default, the base style will provide a nice "active green" 2px outline. But there are times when you may need or want to modify this. Just use the attribute selector first when defining focus styles.

note: Please, if you do this, just be sure it's high-contrast and obvious, this is for better accessiblity after all.

So, instead of:

#myElement:focus {
  border-bottom: 1px solid blue;
}

You'd do:

[data-focus-source='keyboard'] #myElement:focus {
  border-bottom: 1px solid blue;
  outline: none; /* disables the inherited rule */
}

Credit/License

Only slight adaptations have been made from the original script in order to give the application control over its initialization and to make it importable as a CommonJS module.

This is a derivative work of WICG Modality which is licensed according to the W3C Software and document notice and license.