How do I use javascript to press keyboard buttons? (similar to HTMLElement. click () on the mouse)


How can I use javascript to press the keyboard buttons?

For the left mouse button, for example: HTMLElement.click()

We need an analog for the keyboard. And so that you can run it through the devtool developer tool.

P.S. nothing is impossible!

Author: Ilnyr, 2018-12-29

4 answers

Very simple listener, even without jq

document.addEventListener ('keydown', function (event){
    console.log (event);
}); 
var evt = new KeyboardEvent('keydown', {'keyCode':65, 'which':65});
document.dispatchEvent(evt);
 1
Author: AlexS, 2019-01-03 09:39:43

Using Jquery:

var press = jQuery.Event("keypress"); 
press.ctrlKey = false;
press.which = 40; // код клавиши, в данном случае — пробел
$("body").trigger(press);  // имитация
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 1
Author: Ver Nick, 2019-01-03 10:17:27

In a similar situation, I also used the addEventListener event handler. For example, I used the code below to exit the modal window via Esc.

document.addEventListener('keydown', function(e) {
        if (e.keyCode == 27) {
            overlay.style.display = 'none';
            more.classList.remove('more-splash');
            document.body.style.overflow = 'visible';    
        }
    });

Similarly, you can use Enter for your own operations.

 0
Author: carboncheg, 2019-01-05 21:01:16

Click() does not click the mouse button, but triggers the click event handlers in the code. A real mouse click generates several events other than click, such as mousedown, mouseup, etc.

So for the keyboard, it can be keypress, keyup, keydown, as well as the input event, etc.

So, for example, if you need to run keypress on some site to emulate pressing Enter, then it may not work on another site. It all depends on the event handlers on the page.

var e = jQuery.Event("keypress");
e.which = e.keyCode = 13;
$("textarea").trigger(e);
 0
Author: holden321, 2019-01-07 13:26:59