How to simulate a keystroke with jQuery?

Asked

Viewed 4,673 times

4

I wonder if there is any way to simulate pressing keys with jQuery.

For example, when clicking a button, simulate that the "down" and "left" keys were pressed, as if the user had a keyboard.

 $(document).on('click', function (){
       // Simule pressionar as teclas 'down' e 'left' do teclado           
 });

Can you do that? With jQuery, preferably.

For those who are confused, I think the term used in this type of operation (usually by gamers) is bot (robot) for pressing keys.

2 answers

5


You can create the event and then trigger it.

var teclaEsquerda = jQuery.Event("keypress");
teclaEsquerda.ctrlKey = false;
teclaEsquerda.which = 37; //Código da tecla - seta esquerda

$("botao").trigger(teclaEsquerda);

Code of the other arrows:

  • To the top: 38
  • Down: 40
  • Right: 39
  • 1

    Thanks, that’s right +1

  • 1

    Take my answer only as a complement, but yours solves the question :)

4

I will answer my question, but don’t get me wrong. Just consider it as a complement.

As already stated by @Pedrocamarajunior in their excellent response, you can jQuery.Event to create an event.

When I needed to do this, I created an extension for jQuery, so that it would work in a more reusable way.

Below the code:

(function ($){

    $.fn.triggerKeyPress = function (keys)
    {
        var keydownEvent = $.Event("keydown");

        var $self = this;

        $.each(keys, function(index, value) {

            var simulatedKey = $.extend({}, keydownEvent, {which: value, keyCode: value});

            $self.trigger(simulatedKey);
        });

    }

})( jQuery );

To use, just choose the element where you want to simulate the keys:

$('body').triggerKeyPress([37, 40])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.