Add Arrow Key Support

Allow up and down arrow key support for a specified html section. In this example the up+down arrow keys will work for the links.

by Allen N.

HTML

<div>Lorem ipsum dolor amet microdosing blue bottle iceland reprehenderit, raclette mustache dreamcatcher. Tbh raw denim culpa minim ea. Ugh succulents ad est green juice. Health goth PBR&B quinoa in, tofu venmo put a bird on it authentic pabst.</div>

<button>Button One</button>

<div class="arrow-key-support-container">
	<a href="#example-1">Example Link 1</a>
	<a href="#example-2">Example Link 2</a>
	<a href="#example-3">Example Link 3</a>
	<a href="#example-4">Example Link 4</a>
	<a href="#example-5">Example Link 5</a>
</div>

<button>Button Two</button>

SCSS

div, button, a {
	display: block;
	margin: 10px;
	padding: 10px;
}
div {
	max-width: 200px;
}
a {
	display: inline-block;
}

JavaScript

document.addEventListener('keydown', navKeyboardHandler);

// Implement handler to support keyboard-based navigation through the primary nav.
function navKeyboardHandler(e) {
console.log('key pressed');
	var focusElement = $(document.activeElement);
	
	if (focusElement.parents().is('.arrow-key-support-container')) {
		

		if (e.keyCode === 9 // Tab key pressed,
			&& !e.shiftKey === true // and Shift key NOT pressed;
			|| e.keyCode === 40) { // or Down Arrow key, which makes focus travel forwards.
			
			if (!focusElement.is(':last-child')) {
				e.preventDefault(); // Prevent key from normal skip focus or scroll behaviour.
			}
			// Move focus to next item.
			focusElement.next().focus();
				
		}
		
		if (e.keyCode === 9 // Tab key pressed,
			&& e.shiftKey === true // and Shift key IS pressed;
			|| e.keyCode === 38) { // or Up Arrow key, which makes focus travel backwards.
			
			if (!focusElement.is(':first-child')) {
				e.preventDefault(); // Prevent key from normal skip focus or scroll behaviour.
			}
			// Move focus to previous item.
			focusElement.prev().focus();
		}
	}
}