Reputation: 303
I need to trigger a mouse click event via a keyboard key down. So instead of the user clicking a button on the website, they could just push the "Shift" key (or any other) and get the same action as if they clicked on the button with a mouse.
I tried a lot of things from SO but nothing seems to be working - any ideas?
UPDATE I am trying to make the function that is triggered when that element is clicked with the mouse be more accessible so that you don't need to only use your mouse but also a keyboard shortcut - so to trigger it on KeyDown - ie
Markup
<a href="http://www.google.com" class="clickme">LINK</a>
JS
jQuery(document.body).on('keypress', function(e){
if(e.keyCode == 16){
jQuery('.clickme').trigger('click');
}
});
http://jsfiddle.net/0sdesy1x/1/
Upvotes: 0
Views: 2723
Reputation: 17616
Update: I miss understood the question -- here is the proper solution.
$(document.body).on('keydown', function(e){
if(e.keyCode == 16){
window.location = $('.clickme').attr('href');
}
});
What you're looking for is to trigger the default event on your button, which unfortunately is not possible with jQuery, unless they actually click on it. Your solution is to retrieve the "href" value and change the location to the following.
OR
$(document.body).on('keydown', function(e){
if(e.keyCode == 16){
$('.clickme').get(0).click();
}
});
In the second solution we use jQuery to get the jQuery object and to get the actually HTML reference to button reference, then we click() which is a standard JS function.
You could keep your click and add this code. This way when the shift key is pressed you can trigger the button click. Or if you really want to replace, then put your button code in the comment section in the example below.
$(document.body).on('keydown', function(e){
if(e.keyCode == 16){
$('<your button class or id here>').trigger('click');
//or put your button code here...
}
});
You could do something like this.
Upvotes: 3
Reputation: 317
http://blogs.microsoft.co.il/gilf/2012/09/11/back-to-basics-using-keyboard-events-in-javascript/
The above post is a good starter you.
window.addEventListener('keypress', function (e) {
console.log(e.keyCode);
}, false);
the above with give you the keycode for the key pressed - so you can then set an if statement up to check against the key you want to detect to trigger any actions on.
Upvotes: 0