creepy uncle herbert... creepy uncle herbert... - 1 month ago 5
Javascript Question

I can't figure this out, my script has an issue

my issue

window.onkeydown = function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 71) {
alert("hi");
}
};



window.onkeyup = function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 69) {
alert("hi");
}
};


dont mind the following text!! I thought this would be answered somewhere on SO, but I can't find it.

If I'm listening for a keypress event, should I be using .keyCode or .which to determine if the enter key was pressed?

I've always done something like the following:dont mind this text!!

Answer

something like this..

window.onload = function(e) {

  window.addEventListener('keydown', function (e) {
      console.log('keydown: ' + e.keyCode);
      if (e.keyCode == 71) {
        alert("hi");
      }
  });


  window.addEventListener('keyup', function (e) {
      console.log('keyup: ' + e.keyCode);
      if (e.keyCode == 69) {
         alert("hi");
      }
  });

}