Michael Schwartz
Michael Schwartz

Reputation: 8415

Trigger Enter keypress in vanilla JS

I'm trying to trigger an enter keypress event on my input without actually pressing the enter key, more just onload.

I found out that initKeyboardEvent and initKeyEvent are both deprecated even e.keyCode and e.which are being removed from web standards.

I also found this post that goes over how to do this in jQuery. However, I've been trying to figure out how to do this in vanilla JS and no luck.

var txtbox = document.getElementById('txtbox');
txtbox.onkeydown = function(e) {
  if (e.keyCode == 13) {
    alert('enter key pressed');
  }
  e.preventDefault();
};

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyboardEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
<input type="text" id="txtbox" placeholder="trigger enter key press">

Upvotes: 18

Views: 19644

Answers (1)

pato
pato

Reputation: 908

Since initKeyboardEvent is deprecated use constructor instead: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

event.key is not deprecated so we can use key === "Enter"

Also trigger enter on txtbox instead of body

var txtbox = document.getElementById('txtbox');
txtbox.onkeydown = function(e) {
  if (e.key == "Enter") {
    alert('enter key pressed');
  }
  e.preventDefault();
};

var ev = new KeyboardEvent('keydown', {altKey:false,
  bubbles: true,
  cancelBubble: false, 
  cancelable: true,
  charCode: 0,
  code: "Enter",
  composed: true,
  ctrlKey: false,
  currentTarget: null,
  defaultPrevented: true,
  detail: 0,
  eventPhase: 0,
  isComposing: false,
  isTrusted: true,
  key: "Enter",
  keyCode: 13,
  location: 0,
  metaKey: false,
  repeat: false,
  returnValue: false,
  shiftKey: false,
  type: "keydown",
  which: 13});

txtbox.dispatchEvent(ev);

Upvotes: 27

Related Questions