Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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);
};

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