Created
April 1, 2012 19:45
-
-
Save mrcoles/2278078 to your computer and use it in GitHub Desktop.
A reliable jQuery keypress event especially for arrow keys
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
$.fn.safekeypress = function(func, cfg) { | |
cfg = $.extend({ | |
stopKeys: {37:1, 38:1, 39:1, 40:1} | |
}, cfg); | |
function isStopKey(evt) { | |
var isStop = (cfg.stopKeys[evt.keyCode] || (cfg.moreStopKeys && cfg.moreStopKeys[evt.keyCode])); | |
if (isStop) evt.preventDefault(); | |
return isStop; | |
} | |
function getKey(evt) { return 'safekeypress.' + evt.keyCode; } | |
function keypress(evt) { | |
var key = getKey(evt), | |
val = ($.data(this, key) || 0) + 1; | |
$.data(this, key, val); | |
if (val > 0) return func.call(this, evt); | |
return isStopKey(evt); | |
} | |
function keydown(evt) { | |
var key = getKey(evt); | |
$.data(this, key, ($.data(this, key) || 0) - 1); | |
return func.call(this, evt); | |
} | |
function keyup(evt) { | |
$.data(this, getKey(evt), 0); | |
return isStopKey(evt); | |
} | |
return $(this).keypress(keypress).keydown(keydown).keyup(keyup); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks it's seem exactly what I need, can you give an example of use ?