Search code examples
javascriptkeykeycode

I want to alert a value when I press the Esc button in prompt, but I have no idea... (code below)


const login = prompt("Enter username!", "");

if (login === "Admin") {
  prompt("Enter password!");
} else if (login === "" || login.keyCode === 27) {
  alert("Canceled");
} else {
  alert("I don't know you!");
}

This is the error message when I press Esc:

'Cannot read properties of null (reading 'keyCode') at logical-operators.html:77'


Solution

  • when you press ESC the login value will become null so you can check like this:

    if(!login){
      alert('cancled')
    }
    

    or you can add listener to dom if ESC clicked :

    document.addEventListener("keyup", (e) => {
        if (e.key === "Escape") {
          // escape key maps to keycode `27`
          alert('cancled')
        }
      });