Skip to content

Instantly share code, notes, and snippets.

@j-
Created November 7, 2018 04:31
Show Gist options
  • Save j-/fb0eaa0529328cf68c273345948d53aa to your computer and use it in GitHub Desktop.
Save j-/fb0eaa0529328cf68c273345948d53aa to your computer and use it in GitHub Desktop.
Set 'focus' on any HTML element
<!doctype html>
<meta charset="utf-8">
<title>Fauxcus</title>
<nav>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</nav>
<header>
<h1>Page heading</h1>
</header>
<section>
<form>
<label for="input">Input</label><br />
<input type="text" id="input" />
</form>
<button type="submit" id="next">Next</button>
</section>
<footer>
<a href="#">Sitemap</a>
</footer>
<style>
form {
padding: 1em;
background-color: #eee;
}
section {
margin: 2em 0;
}
</style>
<script>
const fauxcus = (() => {
const focusable = document.createElement('div');
focusable.tabIndex = 0;
// TODO: Implement focus detection
const isFocusable = (el) => false;
return (el) => {
if (!(el instanceof HTMLElement)) return;
if (isFocusable(el)) return el.focus();
const { parentNode } = el;
parentNode.insertBefore(focusable, el).focus();
parentNode.removeChild(focusable);
};
})();
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
});
document.querySelector('button').addEventListener('click', (e) => {
e.preventDefault();
const heading = document.querySelector('h1');
fauxcus(heading);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment