Home >Web Front-end >JS Tutorial >Can JavaScript Programmatically Simulate Key Press Events?

Can JavaScript Programmatically Simulate Key Press Events?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 20:48:11333browse

Can JavaScript Programmatically Simulate Key Press Events?

Programmatic Simulation of Key Press Events in JavaScript

Is it feasible to programmatically replicate key press events within a JavaScript framework?

Answer:

Indeed, it is possible to simulate keystroke events using JavaScript. The following code sample, independent of jQuery, is compatible with both WebKit and Gecko-based browsers:

var keyboardEvent = document.createEvent('KeyboardEvent');
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';

keyboardEvent[initMethod](
  'keydown',
  true,
  true,
  window,
  false,
  false,
  false,
  false,
  40,
  0
);
document.dispatchEvent(keyboardEvent);

The above is the detailed content of Can JavaScript Programmatically Simulate Key Press Events?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn