Skip to content

Instantly share code, notes, and snippets.

@ttntm
Created January 17, 2020 12:12
Show Gist options
  • Save ttntm/dfeb21dd823d5fa3a321d3f8c802fb27 to your computer and use it in GitHub Desktop.
Save ttntm/dfeb21dd823d5fa3a321d3f8c802fb27 to your computer and use it in GitHub Desktop.
JavaScript ESC key listener
// document is necessary; window context requires a click into the page body for it to work (at least in Chrome)
document.addEventListener('keydown', function(e){
if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27)){ // if necessary: target specific node with: && (e.target.nodeName=='BODY')
// if necessary: e.preventDefault();
// do something with the ESC button press, i.e. close modal/NAV/lightbox etc.
}
}, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment