How to simulate a jQuery keystroke?

4

I would like to know if there is any way to simulate keystrokes with jQuery.

For example, when you click a button, you simulate that the "down" and "left" keys have been pressed, as if the user had them.

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

Can you do this? 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 keystrokes.

    
asked by anonymous 02.05.2016 / 15:43

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:

  • Up: 38
  • Down: 40
  • Right: 39
02.05.2016 / 15:59
4

I will answer my question, but do not get it wrong. Consider only as a complement.

As already said by @PedroCamaraJunior in your excellent response, you can jQuery.Event to create an event.

When I needed to do this, I created an extension for jQuery to work more reusably.

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, simply choose the element where you want to simulate the keys:

$('body').triggerKeyPress([37, 40])
    
02.05.2016 / 16:06