Recreating the Enter Button in JavaScript

85 Views Asked by At

There is a page in which wherever you press Enter a textbox appears (type text). If you write something in that box and you press Enter the message will be sent. You don't have to be already focused on that box.

What I wanna do is recreate the Enter function. So if I have something already written in that box and run my script the message will be sent.

I tried this

const input = document.querySelector("#messageBox");
const event1 = new KeyboardEvent('keypress', { key: 'Enter' });
const event2 = new KeyboardEvent('keypress', { key: 'l' });
const event3 = new KeyboardEvent('keypress', { key: 'Space' });
const event4 = new KeyboardEvent('keypress', { key: 'Escape' });

messageBox.focus();

setTimeout(() => {
     input.dispatchEvent(event1);
     input.dispatchEvent(event2);
     input.dispatchEvent(event3);
     input.dispatchEvent(event4);
}, 1500)
input.addEventListener('keypress', (event) => {
     console.log("testing this");
     if (event.keyCode === 13) {
          console.log("Enter has been pressed");
     }
     if (event.keyCode === 76) {
          console.log("L has been pressed");
     }
     if (event.keyCode === 32) {
          console.log("Space has been pressed");
          input.dispatchEvent(event1);
     }
     if (event.keyCode === 27) {
          console.log("Escape has been pressed");
     }
})

and saw that none of these events were actually triggered inside the messageBox. When I run the script these 4 keys are pressed but nothing in the messageBox changes. The only thing that changes is in the console in where I see 4 times the "testing this" message. enter image description here

Now if I press L, Enter or Escape in that box, it doesn't show their respective console messages. But if I press space, it does show the "Space has been pressed". enter image description here

Even though I'm new to JavaScript I have searched it a lot and couldn't find anything. I would appreciate any help

1

There are 1 best solutions below

9
Quentin On

The KeyboardEvent constructor documentation says:

key Optional

A string, defaulting to "", that sets the value of KeyboardEvent.key.

It just sets the value of key.

The value of keyCode isn't implicitly set.

Your event listener logs testing this (which you can see) and then tests keyCode.

If you want to trigger an event which you can examine the keyCode of then you need to set keyCode as well as / instead of key.


Note that keyCode is deprecated so your listener shouldn't be using it in the first place.