Skip to content

Instantly share code, notes, and snippets.

@jlsync
Created March 6, 2015 15:43
Show Gist options
  • Save jlsync/9124277967b96e065b1f to your computer and use it in GitHub Desktop.
Save jlsync/9124277967b96e065b1f to your computer and use it in GitHub Desktop.
bkeys - jquery keyboard binding
$ = jQuery
special_codes =
8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl"
18: "alt", 19: "pause"
20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown"
35: "end", 36: "home"
37: "left", 38: "up", 39: "right", 40: "down", 45: "insert"
46: "del"
special_keys = []
special_keys[k] = c for c, k of special_codes
methods =
init: (keydefs, callback) ->
return this.each () ->
$this = $(this)
normals = []
specials = []
# break keys into two groups
for keydef in keydefs
k = _(keydef.split('+')).last()
if special_keys[k]?
specials.push(k)
else
normals.push(k)
_normals = _(normals)
_specials = _(specials)
$this.bind 'keypress', (e) ->
code = e.keyCode || e.which
key = String.fromCharCode(code)
if _normals.include(key)
# could add test for ctrl modifier
# (shift and alt would already be preocessed)
callback.call(this, key, e)
# specials are match on keydown to intercept browser processing
$this.bind 'keydown', (e) ->
code = e.keyCode || e.which
key = special_codes[code]
if _specials.include(key)
# could add test for more key modifiers(i.e. ctrl, alt)
if e.shiftKey
key = "shift+" + key
callback.call(this, key, e)
remove: () ->
return this.each () ->
$this = $(this)
console?.log('not implemented')
$.fn.bkeys = (method) ->
if methods[method]?
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ))
else if typeof method == 'object' or ! method
return methods.init.apply( this, arguments )
else
$.error( 'Method ' + method + ' does not exist on jQuery.bkeys' )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment