Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Enter keypress in vanilla JS

Tags:

javascript

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">
like image 279
Michael Schwartz Avatar asked Aug 09 '18 20:08

Michael Schwartz


1 Answers

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);
like image 143
pato Avatar answered Sep 24 '22 07:09

pato