spatial-navigation-polyfill
Version:
A polyfill for the spatial navigation
69 lines (66 loc) • 3.16 kB
HTML
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="application-name" content="Default Spatial Navigation Behavior">
<meta name="author" content="Jeonghee Ahn">
<meta name="description" content="window.navigate ({dir}) moves the focus in a specific direction.
When the focus moves <b>inside the element with the red border</b>, you can move the focus with <b>WASD keys.</b>">
<link rel="stylesheet" href="spatnav-style.css">
<script src="spatnav-utils.js"></script>
<script src="../../polyfill/spatial-navigation-polyfill.js"></script>
<link class="codestyle" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script type="text/javascript">
let previousTarget;
const init = function(e) {
const WASD_KEY_CODE = {65: 'left', 87: 'up', 68: 'right', 83: 'down'}
// Turn on the spatial navigation heuristic
const container = document.getElementsByClassName('container c1')[0];
container.addEventListener('keydown', function(e) {
const dir = WASD_KEY_CODE[e.keyCode];
if(window.navigate && dir) {
window.navigate(dir);
e.preventDefault();
}
});
};
</script>
</head>
<body onload="init()">
<div style="width:600px; height: 300px; padding: 20px;">
<h4>
<span>spatnav container 1(Document)</span> >
<span class="c1">spatnav container 2</span> >
<span class="c2">spatnav container 3</span>
</h4>
<button class="box" style="top:100px; left:20px;"></button>
<button class="box" style="top:98px; left:50px;"></button>
<div class="container c1" tabindex="0" style="position: relative; left:110px; width:500px; height:180px; --spatial-navigation-contain: contain;">
<button class="box b2" style="top:78px; left:25px;"></button>
<div class="container c2" tabindex="0" style="position: relative; left:110px; width:250px; height:100px; --spatial-navigation-contain: contain;">
<button class="box b3" style="top:40px; left:60px;"></button>
<button class="box b3" style="top:30px; left:200px;"></button>
</div>
<button class="box b2" style="top:-80px; left:300px;"></button>
<button class="box b2" style="top:-90px; left:420px;"></button>
</div>
<button class="box" style="top:-119px; left:400px;"></button>
<button class="box" style="top:-120px; left:650px;"></button>
</div>
<pre class="code-area">
<code id="code">
const redContainer = document.getElementsByClassName("container c1")[0];
redContainer.addEventListener('keydown', function(e) {
const dir = WASD_KEY_CODE[e.keyCode];
if(window.navigate && dir) {
window.navigate(dir);
e.preventDefault();
}
}, true);
</code>
</pre>
</body>
</html>