patternjavascriptMinor
Keypress function conditional
Viewed 0 times
keypressfunctionconditional
Problem
How can I combine these
if statements to make this a little cleaner and be less repetitive?$(document).keydown(function(e){
if (e.keyCode == 38) {
if($html.hasClass('client-loading') || canAnim === false) {
return false;
}
var $prevProj = $('.project-current').prev('.project');
$prevProj.click();
}
if (e.keyCode == 40) {
if($html.hasClass('client-loading') || canAnim === false) {
return false;
}
var $nextProj = $('.project-current').next('.project');
$nextProj.click();
}
// Prevent rapid clicking
if ( e.keyCode == 38 || e.keycode == 40 ) {
canAnim = false;
setTimeout(function(){
canAnim = true;
},2000);
}
});Solution
Here's another one, just for the heck of it
$(document).keydown(function (e) {
var current;
// return early
if( e.keyCode !== 38 && e.keyCode !== 40 ) {
return false;
}
// again, return early
if( $html.hasClass('client-loading') || canAnim === false ) {
return false;
}
current = $('.project-current');
if( e.keyCode === 38 ) {
current.prev('.project').click();
}
if( e.keyCode === 40 ) {
current.next('.project').click();
}
canAnim = false;
setTimeout(function () { canAnim = true; }, 2000);
});Code Snippets
$(document).keydown(function (e) {
var current;
// return early
if( e.keyCode !== 38 && e.keyCode !== 40 ) {
return false;
}
// again, return early
if( $html.hasClass('client-loading') || canAnim === false ) {
return false;
}
current = $('.project-current');
if( e.keyCode === 38 ) {
current.prev('.project').click();
}
if( e.keyCode === 40 ) {
current.next('.project').click();
}
canAnim = false;
setTimeout(function () { canAnim = true; }, 2000);
});Context
StackExchange Code Review Q#18792, answer score: 2
Revisions (0)
No revisions yet.