Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Created April 1, 2012 19:45
Show Gist options
  • Save mrcoles/2278078 to your computer and use it in GitHub Desktop.
Save mrcoles/2278078 to your computer and use it in GitHub Desktop.
A reliable jQuery keypress event especially for arrow keys
$.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);
};
@mikecastrodemaria
Copy link

Thanks it's seem exactly what I need, can you give an example of use ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment