0

Currently I am trying to make it so whenever you click enter, it toggles the ability to use the spacebar. It will by default be set to let you not use the spacebar but when the enter key is hit, that is toggled and you can use it. when you click it again you are unable to use it again.

let toggleee = "false"

document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
if (toggleee = "false") {
    let toggleee = "true"
} else if (toggleee = "true") {
    let toggleee = "false"
}
  }
});

document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
      setTimeout(function() {
    // code to execute after delay
    if (toggleee = "false") {
    window.onkeydown = function(e) {
return !(e.keyCode == 32);
}
} else if (toggleee = "true") {
    return;
}
  }, 500);

  }
})

Instead of doing what its intended to do, it ends up making it so spacebar works once and then when you do the toggle it just never works again. Please help it would be greatly appreciated.

Edit: after doing what some comments told me this is the resulting code. Issue is in comments.

let toggleee = false

document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
if (toggleee === false) {
    toggleee = true
} else if (toggleee === true) {
    toggleee = false
}
  }
});

document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
      setTimeout(function() {
    // code to execute after delay
    if (toggleee === false) {
    window.onkeydown = function(e) {
return !(e.keyCode == 32);
}
} else if (toggleee === true) {
    return;
}
  }, 500);

  }
})
J3B
  • 15
  • 2
  • Don't include `let` when reassigning a variable. It creates a new scope instead of using your original variable. Also use real booleans, not strings – Zach Saucier Jun 29 '22 at 21:39
  • `if (toggleee = "false") {` should be `if (toggleee === "false") {` – Lee Taylor Jun 30 '22 at 00:36
  • I've done what both of you have said. here is the result. It lets spacebar work for the first time before and after you click enter. after that spacebar stops working even when the toggle for it to be turned on is on. any more things that might be wrong? resulting code is in edit of the question – J3B Jun 30 '22 at 20:24

0 Answers0