Created
April 15, 2022 07:02
-
-
Save nfreear/99411278cdc036c3497c59c3c4452ea3 to your computer and use it in GitHub Desktop.
Demo of a keyboard trap.
This file contains 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
<!doctype html> <title> Keyboard trap </title> | |
<style> | |
* { | |
outline-offset: 2px; | |
} | |
input { | |
X-border-radius: .2rem; | |
font-size: medium; | |
padding: .2rem .6rem; | |
margin: 0 .3rem; | |
} | |
.im-trapped .trap input { | |
X-display: inline-block; | |
background: #fdd; | |
border-color: red; | |
outline: 5px solid red; | |
} | |
.trap:after { | |
content: ' ✔️'; | |
margin-right: 1rem; | |
} | |
.im-trapped .trap:after { | |
color: #a00; | |
content: ' ❌'; | |
} | |
input#count { | |
background: #eee; | |
border: 1px dotted #aaa; | |
width: 3rem; | |
text-align: center; | |
} | |
</style> | |
<h1> Keyboard trap </h1> | |
<p> Note: press the <q>Escape</q> key then <q>Tab</q> to escape the keyboard trap! | |
<p><a href="#_before">Link before</a> | |
<p><label class="trap"> I'm a trap! <input id="keyboard-trap" /></label> <label> Count: <input id="count" value="0" readonly /></label> | |
<!-- <p><button id="keyboard-trap"> I'm a trap! </button> --> | |
<p><a href="#_after">Link after</a> | |
<script> | |
const TRAP = document.querySelector('#keyboard-trap'); | |
const COUNT = document.querySelector('#count'); | |
let escape = false; | |
TRAP.addEventListener('keydown', ev => { | |
if (ev.key === 'Tab' && !escape) { | |
escape = false; | |
// Set the keyboard trap! | |
ev.preventDefault(); | |
document.body.classList.add('im-trapped'); | |
// ev.target.classList.add('trapped'); | |
ev.target.placeholder = 'Trapped!'; | |
console.warn('TRAP!', 'Keydown event:', ev.key, ev); | |
COUNT.value++; | |
return; | |
} | |
escape = ev.key === 'Escape'; | |
if (escape) { | |
document.body.classList.remove('im-trapped'); | |
// ev.target.classList.remove('trapped'); | |
ev.target.placeholder = ''; | |
} | |
console.debug('Keydown event:', ev.key, ev); | |
}); | |
TRAP.addEventListener('blur', ev => console.debug('Blur event:', ev)); | |
</script> | |
<pre> | |
NDF, 14-April-2022. | |
</pre> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment