0

I have my program in PHP and Javacript for Firefox


I want to emulate on Javascript a hotkey (ALT + K) without jQuery. I want to send that hotkey to my browser pressing a created button. It is possible?


I have this function on my code but it doesn't work:

try {
    var pressEvent = document.createEvent('KeyboardEvent');
    pressEvent.initKeyEvent("keypress",true,true,null,false,true,false,false,75, 0);
    document.body.dispatchEvent(pressEvent); // Press the key.
} catch (e) {
    alert ("Your browser does not support this example!");
}

Please I need to send this hotkey to the browser to show screen-keyboard.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Reichel
  • 1
  • 1
  • 1
    Maybe this will help you? http://stackoverflow.com/questions/2511388/how-can-i-add-a-javascript-keyboard-shortcut-to-an-existing-javascript-function#answer-2511474 – NewToJS Mar 23 '17 at 09:15
  • You did not understand the question, it's the other way around. I want to push a button on the screen and emulate a reception of the keyboard shortcut (ALT+K) on the browser. Can you help me? Thanks!!!;) – Reichel Mar 23 '17 at 16:03
  • Ah yes, I understand what you mean now! Sorry about that. It isn't something I have ever thought of or had to use before so I don't think I could be of much assistance to you on this one. – NewToJS Mar 24 '17 at 00:01

1 Answers1

0

Something like that:

function simulateKey() {
  jQuery('input')
    .trigger({
      type: 'keypress',
      which: 'x'.charCodeAt(0),
      shiftKey: true
    })
}

$('input').on('keypress', (e) => {
  console.log(e.which, e.shiftKey);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input" />
<button onclick="simulateKey()">trigger</button>
felixmosh
  • 32,615
  • 9
  • 69
  • 88