Skip to content

Instantly share code, notes, and snippets.

@FrankHouweling
Created April 29, 2014 17:08
Show Gist options
  • Save FrankHouweling/11406334 to your computer and use it in GitHub Desktop.
Save FrankHouweling/11406334 to your computer and use it in GitHub Desktop.
Javascript Keystroke Shortcuts
<a href="action/link/" data-shortcut="m">
<button type="button" class="btn btn-success">Action Button</button>
</a>
$(document).ready(function(){
/*
* Data-shortcut Shorthand key-combinations for URL's
*/
var shortHands = [];
$.each($('a[data-shortcut]'), function(key, elem){
var shortcut = $(elem).attr('data-shortcut');
shortHands.push({
key : shortcut,
action : $(elem).prop('href')
});
if( $(elem).find('button').length > 0 ){
var button = $(elem).find('button')[0];
$(button).html( $(button).html().replace(new RegExp(shortcut, "i"), function(match){
return "<u>" + match + "</u>";
}) );
} else{
$(elem).html( $(elem).html().replace(new RegExp(shortcut, "i"), function(match){
return "<u>" + match + "</u>";
}) );
}
});
$(window).keydown(function (e){
if( e.metaKey ){
var code = e.keyCode || e.which;
var pressedKey = String.fromCharCode(code);
var foundAction = false;
$.each(shortHands, function(key, obj){
if( obj.key.toLowerCase() == pressedKey.toLowerCase() ){
e.preventDefault();
window.open(obj.action, '_self');
return false;
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment