I am trying to bind a handler to an event. The event is a keydown function. The handler will listen for hit variables to produce one of two conditions. The 1st condition (odd number of hits) will perform 1 function, the 2nd (even number of hits) will perform another function. To elaborate, the 1st function will scroll to one element, the 2nd will scroll to another element. My syntax may be the wrong approach, but it works for the 1st condition, but not the 2nd. I think I have the conditional statement in the wrong place. How can I rewrite this to work as intended? Thank you kindly, in advance!
$(document).keydown(function(e) {
switch (e.which) {
case 37:
break;
case 38:
break;
case 39:
break;
case 40:
//bottom arrow key
var hits = 0;
if (hits % 2 !== 0) {
$('#wrap').animate({
scrollTop: $("#scrollToHere").offset().top
}, 2800);
}
else {
$('#wrap').animate({
scrollTop: $("#scroll2ToHere").offset().top
}, 2800);
}
hits++;
return false;
break;
}
})?
*I moved "var hits = 0;" to the top, but it only works! But is there a way I can reset the whole thing after every two hits? I want to reset because when there is a bug and if I press a 3rd time it scrolls to the very top of the page, where there is no element to make it scroll to the top. Why would it scroll to the top of the page if I never scripted it to do so?? *