A smart spatial navigation for JS
npm install bishop-jsThe main idea is based on the document.elementFromPoint method. Although this functionality is marked as experimental, seems that all current browsers and browser based enviroments (such as SmartTV platforms) support it.
For more details, refer https://developer.mozilla.org/pl/docs/Web/API/Document/elementFromPoint
Navigation also support mouse/pointer.
It's as simple as typing:
npm install bishop-js
Alternatively, you can just download the bishop.js file and use it.
Simply, require the module:
var bishop = require('bishop-js');
Then, init the module.
bishop.init();
In init, bishops adds event listeners to body. From that point the module is ready to go.
In the simplest scenario, add CSS class navigable to any element, that should be navigable. The code will do the
rest.
The module will add the class focused to item that was focused.
You can force manually to focus/blur a navigable event by using bishop.focus and bishop.blur methods. Notice, that
only one item can be focused. Therefore, focus will call blur automatically on currently active element.
To start using the navigation, simply call focus on navigable element when ready.
As a second argument, blur and focus accepts type, which should indicate the origin of the action. Default are:'mouse' and 'keyboard'. You can pass custom types, if needed.
bishop.blur(oldElement, 'keyboard');
bishop.focus(newElement, 'keyboard');
CustomEvent named navigate on the element from which navigation was triggered. keyCode property, similar to native browser keydown event. Now, notice that this custom* You can react on the navigate event in the current state of navigation, not in the future state.
* The navigate event is cancelable. So you can bypass the default navigation in special cases, simply by calling
event.preventDefault().
The navigate event bubbles up through DOM, similar as native keydown event.
var firstItem = document.querySelector('#first');
var lastItem = document.querySelector('#last');
// Add listener for navigable event
lastItem.addEventListener('navigate', function (event) {
// down key pressed
if (event.keyCode === 40) {
// focus first item
bishop.focus(firstItem);
// Prevent default action
event.preventDefault();
}
});
blur event will be triggered on said element. Same goes for focus event. Bothtype property will containmouse and keyboard. This is handy, as some components (for example - scrollablenav-up, nav-down, nav-left and nav-right with value of CSS
By default, bishop-js will consider a navigable every element that have navigable CSS class. You can override this
behaviour by passing your own implementation of isNavigable method. It takes a DOM element as a argument and returns
true or false. Example:
// Every 'a' is navigable
bishop.isNavigable = function (element) {
return element.tagName === 'a';
}