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

Can JavaScript Programmatically Simulate Key Press Events?

Barbara Streisand
Release: 2024-12-24 20:48:11
Original
282 people have browsed it

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template