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" }));
}
}
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.