2

Id like to give thanks in advance for any time and effort spent on this. Ok so I have a script thats supposed to simulate a key press down event after 3 seconds once the page is loaded. I inteded for this keypress to run a keyboard shortcut but all it does it just press the key. How can i get it to actually run the shortcut once pressed? Not sure if this is even possible. Again thanks.

<script>
 setTimeout( function(){
// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function(character) {
  // Internally calls jQuery.event.trigger
  // with arguments (Event, data, elem). That last arguments is very important!
  jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};

jQuery(document).ready( function($) {
  // Bind event handler
  $( 'body' ).keypress( function(e) {
    alert( String.fromCharCode( e.which ) );
    console.log(e);
  });
  // Simulate the key press
  $( 'body' ).simulateKeyPress('z');
});
 }, 3000); //3 seconds

</script>

<script type="text/javascript">
// define a handler
function doc_keyUp(e) {

    // this would test for whichever key is 40 and the ctrl key at the same time
    if (e.ctrlKey && e.keyCode == 122) {
        // call your function to do the thing
        pauseSound();
    }
}
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);
</script>
user1480167
  • 73
  • 1
  • 4
  • 10

2 Answers2

11

If you're trying to fire some browser or system wide keyboard shortcut then it's a dead end - it can't be done for security reasons. If it would be possible, you would have pages all over the Internet that would (for example) add themself to your bookmarks without even asking (by firing CTRL+B shortcut using Javascript).

WTK
  • 16,583
  • 6
  • 35
  • 45
  • ok thanks for clairfying. I kind figured...but wanted to make extra sure...........So i couldnt even create a button that people can click that would set off a keyboard shorcut? – user1480167 Dec 11 '12 at 13:28
  • Nope, using just Javascript you can't do that. – WTK Dec 11 '12 at 13:30
  • im fixing to mark this as answred by you...what type of script other than javascript would you recommened to be used to achieve somthing along these lines? – user1480167 Dec 11 '12 at 13:33
  • i do apologize i meant to type jquery in my title not javascript. – user1480167 Dec 11 '12 at 13:35
2

you don't add your handler first....do that

jQuery(document).ready(function($) {
    // Bind event handler
    $('body').keypress(function(e) {
        alert(String.fromCharCode(e.which));
    });
});
jQuery.fn.simulateKeyPress = function(character) {
    jQuery(this).trigger({
        type: 'keypress',
        which: character.charCodeAt(0)
    });
};

setTimeout(function() {
    $('body').simulateKeyPress('z');
}, 3000); //3 seconds

example to test: http://jsfiddle.net/x8a25/1/

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100