ToleFocus
JavaScript Framework agnostic Focus Manager coded in TypeScript
This library is in alpha state, use it at your own risk. Pull requests are welcome.
There aren't test. I would love it if you could make them.
ToleFocus is a small library to manage focus on JavaScript web applications. ToleFocus use ES6 methods, like array.findIndex
, and require some polyfill like core-js in order to work in old browsers, like IE.
ToleFocus is highly inspired on Angular Focus Manager coded by Rob Tylor.
Usage
To enable the focus manager you have to import focusManager
from tolefocus
module and call enable
method.
import {focusManager} from "tolefocus";
focusManager.enable();
This load the content of body
tag searching for ToleFocus attributes.
You can enable the built in DOM observer witch use MutationObserver in order to detect the DOM changes.
import {focusManager, focusObserver} from "tolefocus";
focusManager.enable();
focusObserver.enable();
ToleFocus handles by default the TAB key in the common focusables controls and sends focus to the next or previous control.
Setting focus order
You can set the focus order:
<input />
<input />
<input focus-order="2" />
Focus groups
You can create focus groups where each element can to have his own focus-order in the group.
<div focus-group>
<input />
<div focus-group focus-order="1">
<input />
<input />
<input />
</div>
<input />
<input focus-order="2" />
</div>
<div focus-group focus-order="1">
<input />
<input />
<input />
</div>
Focus loopback control
You can control the group loopback, you can set the head and tail behaivor. When behaivor is "stop" the focus doesn't go to the next element, the foucus stops in the last or first element. When behaivor is "loop" the focus go from last to first element in the group or from the first to the end element.
<div focus-group="loop">
<input />
<input />
<input />
</div>
<div focus-group="stop">
<input />
<input />
<input />
</div>
<div focus-group="stop loop">
<input />
<input />
<input />
</div>
Non-selectable elements
You can send focus to other controls like div
or spans
, you have to set focus-order
attribute.
<div focus-order>
</di>
<input />
<div focus-order="2">
</di>
Autofocus
You can set an element as autofocus to set focus on it automatically. If you have the focusObserver
enabled the element will focus when it's added to the DOM.
<input />
<input />
<input autofocus />
If you want to hide a element and get focused when it becomes visible you can set observe
value to autofocus
attribute.
<input />
<input />
<input autofocus="observe" style="display: none" />
<button onclick="showHiddenInput()">Show</button>