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!