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();