Created
April 29, 2014 17:08
-
-
Save FrankHouweling/11406334 to your computer and use it in GitHub Desktop.
Javascript Keystroke Shortcuts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<a href="action/link/" data-shortcut="m"> | |
<button type="button" class="btn btn-success">Action Button</button> | |
</a> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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