javascriptkeycodeonkeydownonkeypress

Pressing specific keys to do certain things in JavaScript works in Chrome but not Firefox


I'm using 2 functions to detect whether a pressed key matches what I want, and if so, do something. It works like a charm in Chrome, but neither function works in Firefox. Is there a way I can make it work there too?

document.onkeypress = function() {
  if (event.charCode == 49) {
    alert("You pressed 1!");
  }
  if (event.charCode == 50) {
    alert("You pressed 2!");
  }
  if (event.charCode == 51) {
    alert("You pressed 3!");
  }
  if (event.charCode == 52) {
    alert("You pressed 4!");
  }
}

document.onkeydown = function() {
  if (event.keyCode == 122) {
    alert("You pressed F11!");
  }
}
<span>Press 1, 2, 3, 4 and F11 to launch different events.</span>


Solution

  • You forget to declare event argument. Perhaprs Chrome do this automatically. That works in both browsers-

    document.onkeypress = function(event) {
      if (event.charCode == 49) {
        alert("You pressed 1!");
      }
      if (event.charCode == 50) {
        alert("You pressed 2!");
      }
      if (event.charCode == 51) {
        alert("You pressed 3!");
      }
      if (event.charCode == 52) {
        alert("You pressed 4!");
      }
    }
    
    document.onkeydown = function(event) {
      if (event.keyCode == 122) {
        alert("You pressed F11!");
      }
    }