JavaScript Press Enter Key Twice With Different Actions After Each Keypress

3.3k Views Asked by At

I need help pressing the Enter key twice with a different action occurring after each keypress in pure JS (no jQuery), for example:

  • Press Enter
  • One action happens
  • Press Enter again
  • A different action happens

I can get the first action working, just not the second. Here's my code:

var enterPressed = 0;
window.onkeydown = function (e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    if (enterPressed === 0) {
      enterPressed = 1;
      e.preventDefault(); 
      console.log("Enter pressed once. enterPressed is " + enterPressed);
    } else if (enterPressed === 1) {
      e.preventDefault(); 
      console.log("Enter pressed twice. enterPressed is " + enterPressed);
    }
   }
 };

Here's a Plunk.

Any idea what I'm doing wrong? Thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

You are throwing away all JS code when you write on "document".

You need to put that answer on another element like a , document.getElementById('result') and then write the result to that element.

Here is your plunk good sir

var enterPressed = 0;
window.onkeypress = function (e) {
 var keyCode = (e.keyCode || e.which);
 if (keyCode === 13) {
  alert('key');
  if (enterPressed === 0) {
   enterPressed++;
   document.getElementById("result").innerHTML = "Enter pressed once. enterPressed is " + enterPressed;
  } else if (enterPressed === 1) {
   e.preventDefault(); 
   document.getElementById("result").innerHTML = "Enter pressed twice. enterPressed is " + enterPressed;
  }
 return;
 }
};