3

I want to press char by java script instead of keyboard (just for my education). I have input and I want to press key inside it, but it doesn't work (I know that initKeyboardEvent is only in Chrome, I use Chrome), what is wrong in this code?

<input id="edit">
<script>
    var inp = document.getElementById('edit');
    inp.focus();

    var ev = document.createEvent('KeyboardEvent');

    ev.initKeyboardEvent(
        'keypress', true, true, window, false, false, false, false, 49, 0);

    document.body.dispatchEvent(ev);
</script>
Jacek
  • 11,661
  • 23
  • 69
  • 123

1 Answers1

0

Purely experimental and because it got me interested... and because you tagged jQuery... you COULD create your own virtual keyboard and hide it, then listen for each click event. You could then just use jQuery's trigger() function for any key you wish to simulate...

HTML

<div id="keyboard">
   <button id="char-65" class="keyboard">&#65;</button> // A
   <button id="char-66" class="keyboard">&#66;</button> // B
   // ......
   <button id="char-125" class="keyboard">&#125;</button> // }
   <button id="char-126" class="keyboard">&#126;</button> // ~
</div>

CSS

#keyboard{
    display:none
}

jQuery

$('.keyboard').on('click', function(ev){

     switch(ev.target.id){
          case 'char-65': // do whatever
          break;
          case 'char-66': // do whatever
          break;
     }
});

Then just trigger your buttons...

$('#char-65').trigger('click');
$('#char-66').trigger('click');

UPDATE:

Was looking around at better solutions and my answer get's totally owned by this

function simulateKeyPress(character) {
  $.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}

simulateKeyPress("A");
simulateKeyPress("B");
An0nC0d3r
  • 1,275
  • 13
  • 33
  • Thanks for your answer :) I tagged post with 'jQuery', becouse I hopped more people could see my question. Could you find bug in my code, why it not working? – Jacek Dec 21 '15 at 20:14
  • No, although I did read earlier that there is a known bug in Chrome when using 'keypress'... have you tried 'keydown' to see if works? – An0nC0d3r Dec 21 '15 at 20:20