0

I want to fire a Tab keyboard event when Enter is pressed.

What am I doing wrong? I followed this explanation.

function enterToTab(e) {
    if (e.key == "Enter") {
        console.log(e.key);
        e.target.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab" }));
    }
}
Ivan
  • 1,967
  • 4
  • 34
  • 60

1 Answers1

0

The solution seems to be working, there has to be something special in your case.

let div = document.querySelector("#main");

div.addEventListener("keydown", (e) => {
  if (e.key === "Tab") {
    if (e.target.style.background === "lightblue") {
      e.target.style.background = "pink"
    } else {
      e.target.style.background = "lightblue"
    }
  }
})

function enterToTab(e) {
  if (e.key == "Enter") {
    div.dispatchEvent(new KeyboardEvent("keydown", {
      key: "Tab"
    }));
  }
}

document.addEventListener("keydown", enterToTab)
#main {
  width: 200px;
  height: 200px;
  background: lightblue;
}
<div id="main"> mouse click here then press Enter </div>
Alan Omar
  • 4,023
  • 1
  • 9
  • 20