Skip to main content

Javascript - Event on Pressing Keyboard

Updated 1 min readMarkdown
Javascript - Event on Pressing Keyboard

Simple way to detect keyboard pressed is by injecting event listerner, in this case we will detect escape key.

// Add the event listener when needed.
document.addEventListener('keydown', OnKeyboardPressed);

const escPressed = () => { 
  // Remove event after pressed or you can remove on any other events
  document.removeEventListener('keydown', OnKeyboardPressed);
};

// method to listen to the event
const OnKeyboardPressed = (e) => e.key === 'Escape' && escPressed();

References:

About the author

  • I wrote these tutorials for myself in future when I forget for the next steps.

No comments yet. Be the first to comment.

More from this blog