How can I simulate a keypress in JavaScript? [duplicate]
I’m trying to find a way to simulate a keypress.
For example, when function launched, the key “Arrow Down” should be pressed and so the webpage should be slightly scrolled.
I’m interested only in Chrome, and both jQuery or plain JS will be appropriate. (Plain JS will be more preferable).
That’s one of the code examples I tried:
var e = $.Event("keydown", { keyCode: 40}); // 40 = down arrow
$("body").trigger(e);
// When I launch it the console, nothing happens. The page is not scrolled.
// May be I missed some obvious?
I searched and found the following related questions, but the solutions did not work for me:
- Definitive way to trigger keypress events with jQuery
- Firing a Keyboard Event in JavaScript
- How to trigger event in JavaScript?
- Simulate left and right arrow key event with javascript
- Simulate Keypress With jQuery
- Simulating a Keypress Event from Javascript Console
- Simulate JavaScript Key Events
In other words
Using AutoHotkey, you can easily make something like:
Down::
Send, {Up}
Then, if you press Down
arrow key, it will be triggered Up
. I just want to implement it with JS.
As @rfsbsb pointed out from: Jquery script for simulated key press down not running keyboard shortcut
If you’re trying to fire some browser or system wide keyboard shortcut
then it’s a dead end – it can’t be done for security reasons. If it
would be possible, you would have pages all over the Internet that
would (for example) add themself to your bookmarks without even asking
(by firing CTRL+B shortcut using Javascript).
Using this answer, I managed to change the code a bit and I think I got what you are looking for?
Code:
jQuery(document).ready(function($) {
$('body').keypress(function(e) {
if(e.which == '40')
$('body').animate({scrollTop: '100px'});
});
});
jQuery.fn.simulateKeyPress = function(character) {
jQuery(this).trigger({
type: 'keypress',
which: character
});
};
setTimeout(function() {
$('body').simulateKeyPress(40);
}, 1000);
Here is a sample starting from @Haring10’s example:
https://jsfiddle.net/po33vfb4/4/
$('body').keydown(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if(e.which == 40) {
window.scrollBy(0, -100);
} else {
window.scrollBy(0, 100);
}
});
Triggering keydown-keyup-keypress programatically does not seem to have the efect of scrolling. The above sample can be customized to add animations.