Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Can i shorthand these ‘if statements’? Re: Can i shorthand these ‘if statements’?

#104898
Mottie
Member

I agree with Jamy, don’t worry too much about efficiency. If it runs fast enough in IE7 then it’s good.

I just realized the thing that is missing in the code… it needs a filter to allow alphabetic keys through and a return false at the end (demo).

var allowed = {
key: [116],
ctrl: [65, 67, 86, 88, 90, 97, 99, 118, 120, 122],
alt: []
};

$(document).on({
keydown: function(event) {
var k = event.which;
// regular key
if ($.inArray(k, allowed.key) >= 0) {
log('allowed ' + k);
return true;
}
if (event.ctrlKey && $.inArray(k, allowed.ctrl) >= 0) {
log('allowed ctrl+' + k);
return true;
}
if (event.altKey && $.inArray(k, allowed.alt) >= 0) {
log('allowed alt+' + k);
return true;
}
// allow 0-9, a-z and A-Z
if ((!event.ctrlKey || !event.altKey) &&
(k >= 48 && k <= 57) ||
(k >= 65 && k <= 90) ||
(k >= 97 && k <= 122)) {
log('allowed ' + k);
return true;
}
return false;
}
});​