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:
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.
We use event handlers to simulate keypress events in JavaScript.
To simulate native-language keystrokes, you can also use the [Xnn] or [Dnn] constants in the string passed to the Keys method. nn specifies the virtual-key code of the key to be “pressed”. For instance, [X221]u[X221]e will “type” the u and e characters with the circumflex accent.
The answer is: There is no way to programmatically trigger input keys in the sandboxed browser environment under normal circumstances.
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
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?
here is my jsfiddle
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With