0

Is it possible to trigger a keyboard shortcut with jQuery? Example: execute the Shift Key + Space-bar.

$("body").on("click", function(){
  var e = jQuery.Event("keydown");
  e.shiftKey = true;
  e.which = 32;   
  $("body").trigger(e);  
});
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
yer rp
  • 55
  • 7
  • Try to refer to this one : https://stackoverflow.com/questions/3834175/jquery-key-code-for-command-key/3834210 Hope this help :) – emjr Sep 23 '17 at 04:12

1 Answers1

1

Yep, you can bind to keydown event, and when appropriate combination is found, you could trigger desired event on the DOM.

In the snippet below, Shift + Space triggers the button click.

$("body").on("keydown", function(e){
  if(e.shiftKey && e.which == 32) {
    $("#button").click();
  }
});

function doSomething() {
  alert("Button was clicked");
}

function triggerShiftSpace() {
  var event = $.Event("keydown");
  event.shiftKey = true;
  event.which = 32;
  $("body").trigger(event);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button" onclick="doSomething()">
  Don't click me!
</button>

<button id="button" onclick="triggerShiftSpace()">
  Shift + Space
</button>
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • It is possible to do it in reserve where a button click triggers Shift + Space? – yer rp Sep 23 '17 at 13:22
  • @yerrp Yup, I've updated the answer to show how you could do that. See the part in `setTimeout`. – Nisarg Shah Sep 23 '17 at 13:34
  • I meant to type "reverse" as in the click button triggers Shift + Space – yer rp Sep 23 '17 at 15:04
  • Yep. I updated the answer. Is that what you are looking for? – Nisarg Shah Sep 23 '17 at 15:07
  • I assume it works but I can't get it to run, https://jsfiddle.net/1u8urv7p/ Shift + Space shortcut on a website scrolls the page up. My idea was to trigger the shortcut with a mouse click. – yer rp Sep 23 '17 at 16:35
  • Here's the updated fiddle: https://jsfiddle.net/1u8urv7p/1/. Also, on a website, you can scroll using [`.scrollTop`](https://api.jquery.com/scrollTop/) method. – Nisarg Shah Sep 24 '17 at 06:01