Created
August 19, 2012 15:43
-
-
Save eric-wood/3395522 to your computer and use it in GitHub Desktop.
Give it focus and it'll capture keyboard shortcuts kind of like the widgets you see in OS X apps. Useful for letting users set hotkeys. I should probably turn this into a jQuery plugin one day. Let me know if you have any suggestions or code critiques!
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
<h4>Click on the box and enter a new keyboard shortcut:</h4> | |
<input id="shortcut-box"><button id="clear-shortcut-box">clear</button> |
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
currentVal = {}; | |
KeyBox = { | |
init: function(opts) { | |
var elem = opts.elem; | |
// clear the text field when the user clicks on it | |
elem.focus(function(event) { | |
$(event.target).val(''); | |
}); | |
// set to whatever the last value was on blur | |
elem.blur(function(event) { | |
var target = $(event.target); | |
if(currentVal === {}) { | |
target.val(''); | |
} else { | |
target.val(currentVal.str); | |
} | |
}); | |
elem.keyup(function(event) { | |
event.preventDefault(); | |
var target = $(event.target); | |
target.blur(); | |
// generate string to place in box | |
var str = ''; | |
// TODO: cross-OS shenanigans, iirc meta isn't | |
// always the same as the command key | |
if(event.metaKey) { | |
str += 'Cmd + '; | |
} | |
if(event.ctrlKey) { | |
str += 'Ctrl + '; | |
} | |
if(event.altKey) { | |
str += 'Alt + '; | |
} | |
if(event.shiftKey) { | |
str += 'Shift + '; | |
} | |
str += String.fromCharCode(event.keyCode); | |
target.val(str); | |
currentVal = { | |
str: str, | |
event: event | |
}; | |
}); | |
// TODO: add the clear button automagically? | |
$('#clear-shortcut-box').click(function(event) { | |
elem.val(''); | |
currentVal = {}; | |
}); | |
} | |
} | |
$(function() { | |
KeyBox.init({ | |
elem: $('#shortcut-box'), | |
handler: function(event) { console.log(event) } | |
}); | |
}); |
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
body { | |
font-family: sans-serif; | |
} | |
#shortcut-box { | |
border-radius: 3px; | |
border: solid #333 1px; | |
padding: 5px; | |
width: 200px; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment