0

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

FIDDLE

Above is a link to a demo, there is a nasty bug which you can see.

The only thing I can think of is that the following should be revised for the second event:

.offset().top
3
  • var hits = 0; you are declaring the variable on every keydown Commented Oct 20, 2012 at 22:21
  • Hits will always be 0 if you use: var hits = 0; Commented Oct 20, 2012 at 22:21
  • As per your question's update, simply put if (hits == 2) hits = 0; before the return false and it should work fine. Commented Oct 20, 2012 at 23:32

2 Answers 2

2

declare hits outside your keydown function so it doesn't get reset to 0 each time.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, I put "var hits = 0;" above function. It worked, but only for 1 loop; the second time around, and so forth, the 1st condition is ignored.
console.log(hits) to make sure it is incrementing.
Thanks, I tried that but doesn't seem to make a difference either way. Here is a demo so you all can see what is going on with this bug. jsfiddle.net/FTCQG/11
1

No, not the condition is in the wrong place but your variable declaration and initialisation. If you do

hits = 0;
if (hits % 2 !== 0) …

the condition will obviously be always false.

Move the declaration outside the scope of your event handler function, and don't reset it each time right before you query it.

3 Comments

I moved var hits = 0; to the top, but it makes the loop not work after the 2nd test. How can I reset the whole thing after 2 hits?
Why do you want to reset it, it`s a counter and you have a condition to do something every even/odd run?
It needs to be reset because the whole thing is inside a slide show. Think of this inside slide ONE. When the user leaves slide ONE and goes to slide TWO or THREE then the variable needs to be refreshed so when going back to ONE I can avoid making hits stuck at an odd number, thus avoiding the skipping of the first keydown event. I resolved it on this page: stackoverflow.com/questions/12993914/… ... Thanks for your help though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.