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’?

#104876
Mottie
Member

Hi John!

I’m sure there is an even more efficient way than this method (maybe using a for in loop), but this is what I came up with (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) {
return true;
}
// ctrl keys
if (event.ctrlKey && $.inArray(k, allowed.ctrl) >= 0) {
return true;
}
// alt keys - added just in case ;)
if (event.altKey && $.inArray(k, allowed.alt) >= 0) {
return true;
}
}
});‚Äč