Created
October 27, 2018 06:26
-
-
Save asvny/7bdc3b375ac3709beb65994b3f2ef4e1 to your computer and use it in GitHub Desktop.
FocusTrap custom component using LitElement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
html, | |
LitElement | |
} from "https://unpkg.com/@polymer/[email protected]/lit-element.js?module"; | |
const KEYCODE_TAB = 9; | |
class FocusTrap extends LitElement { | |
constructor() { | |
super(); | |
this.handleFocus = this.handleFocus.bind(this); | |
this.addEventListener("keydown", this.handleFocus); | |
} | |
createRenderRoot() { | |
return this.attachShadow({ mode: "open", delegatesFocus: true }); | |
} | |
handleFocus(e) { | |
var focusableEls = this.querySelectorAll( | |
'a[href], button, textarea, input[type="text"], input[type="radio"], input[type="checkbox"], select' | |
), | |
firstFocusableEl = focusableEls[0], | |
lastFocusableEl = focusableEls[focusableEls.length - 1]; | |
var isTabPressed = e.key === "Tab" || e.keyCode === KEYCODE_TAB; | |
if (!isTabPressed) { | |
return; | |
} | |
if (e.shiftKey) { | |
/* shift + tab */ if (document.activeElement === firstFocusableEl) { | |
lastFocusableEl.focus(); | |
e.preventDefault(); | |
} | |
} /* tab */ else { | |
if (document.activeElement === lastFocusableEl) { | |
firstFocusableEl.focus(); | |
e.preventDefault(); | |
} | |
} | |
} | |
render() { | |
return html` | |
<div class="trap"> | |
<slot></slot> | |
</div> | |
`; | |
} | |
} | |
customElements.define("focus-trap", FocusTrap); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment