Reputation: 55
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);
});
Upvotes: 0
Views: 2942
Reputation: 14561
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>
Upvotes: 1