Home › Forums › JavaScript › Can i shorthand these ‘if statements’?
- This topic is empty.
-
AuthorPosts
-
June 24, 2012 at 3:19 am #38639
JohnMotylJr
ParticipantHowdy, is there any kind of
ternary
orshorthand
method for this. Maybe even a switch case?$document.on({
keydown: function(event) {
// F5
if (event.which == 116) { return true; }
// Ctrl + A
if ((event.ctrlKey && event.which == 097) || (event.ctrlKey && event.which == 65)) { return true; }
// Ctrl + X
if ((event.ctrlKey && event.which == 120) || (event.ctrlKey && event.which == 88)) { return true; }
// Ctrl + C
if ((event.ctrlKey && event.which == 099) || (event.ctrlKey && event.which == 67)) { return true; }
// Ctrl + Z
if ((event.ctrlKey && event.which == 122) || (event.ctrlKey && event.which == 90)) { return true; }
// Ctrl + V
if ((event.ctrlKey && event.which == 118) || (event.ctrlKey && event.which == 86)) { return true; }
//.... etcJune 26, 2012 at 10:52 am #104876Mottie
MemberHi 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;
}
}
});June 26, 2012 at 12:16 pm #104885JohnMotylJr
Participant@Mottie
I am totally going to check this out now.
I am somewhat new to the whole js / jQuery thang but is there any way to test javascript / jQuery code for efficiency? Because whether i run this as a loop, if stack, switch case, on vs live vs keydown etc, Im not sure if im trying to make this more difficult on myself.
June 26, 2012 at 4:22 pm #104898Mottie
MemberI 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;
}
}); -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.