-1

I have a couple of buttons on my simple html web page which call some javascript:

  <input type="image" src="button_start.png" onClick="start();">
  <input type="image" src="button_stop.png" onClick="stop();">
  <input type="image" src="button_reset.png" onClick="reset()">

What I want is to be able to press three separate keyboard keys and just have them 'press' the buttons or call the javascript code. What's the easiest way to go about this?

  • Thanks Nile. I searched, but apparently not well enough. I ended up modifying op's code here: http://stackoverflow.com/a/4929676/2509899 and it works great. – user2509899 Jun 21 '13 at 17:57

4 Answers4

2

You can add key listeners, and call the appropriate functions depending on the key pressed.

It is however very difficult due to security to actually dispatch/simulate button click events.

Below an example with javascript that will call start() when key with keycode 13 is pressed.

You can see the codes here: http://www.quirksmode.org/js/keys.html

Using Javascript

window.addEventListener('keypress', function (e) {
    if (e.keyCode !== 13) {
        start();
    }
}, false);
Menelaos
  • 23,508
  • 18
  • 90
  • 155
0

You may try this

window.addEventListener('load', function(e){
    var keys = { 't' : 'start', 's' : 'stop', 'r' : 'reset' };
    window.addEventListener('keypress', function (e){
        var fn = String.fromCharCode(e.which||e.keyCode);
        if(fn in keys) window[keys[fn]]();
    });
});

Press t for start, s for stop and r for reset. Also, you can change the keys, if you want to set the s key for start function then change the key in the keys object accordingly, but one key should be used for one function.

DEMO.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
-1

You can listen on the keydown event and you can use the keycode to identify which key was pressed to execute the functions. see https://developer.mozilla.org/en-US/docs/Web/API/event.keyCode

Hando
  • 1
  • 2
-1

Use the shortkey jquery plugin ShortKey Plugin

$(document).shortkeys({
  's': function () { start(); },'o': function () { stop(); },'r': function () { reset(); }
});
Usual Suspect
  • 601
  • 1
  • 8
  • 19