1

I am trying to scroll to 2 different elements in a keydown event, 1st element on the first press, 2nd element on second press, and repeat the event after every 2 presses (or hits). I created a JSFiddle demo, linked below.

FIDDLE

As you can see, it will not scroll to the bottom element on the second press (or hit). The only thing I can think of is using something else besides ".offset().top" for the second event. But if some of you JS gurus look at my code you may see the bug or perhaps another solution for the desired effect. Thanks in advance!

.offset().top ???

MAIN BUG SOLVED, but new bug revealed.. Is there a way to reset the hit variable to ZERO if the user clicks the UP arrow??

NO MORE BUGS! FEEL FREE TO USE THIS SCRIPT ALL YOU WANT!

1 Answer 1

0

See the definitions of offset

Get the current coordinates of the first element in the set of matched elements, relative to the document.

the problem here is when you animated the #wrap element, its offset changes the easiest solution is to get its position beforehand, see my edited JSfiddle. Add the following two lines of code, and do the animation according to spot1/spot2. The switch case executes fine.

var spot1 = $("#scrollToHere2").position().top;
var spot2 = $("#scrollToHere").position().top;
Sign up to request clarification or add additional context in comments.

6 Comments

Great solution, that worked out wonderfully. I would vote up if my rep was up. Who ever else reads this, feel free to use my (and fin's) code for your future websites, and vote up, this is very useful.
Fin, is there any way to reset the variable to ZERO if pressing the UP arrow, in case a user clicks the UP arrow after only clicking the DOWN arrow once, instead of clicking it twice?
Hmm, looks like we both resolved it in different ways. You added (!firstdown) but I simply added hits = 0. Which way is better? I do not know that syntax.
Or, not syntax, but I didn't know you could play with a variable like that, cool stuff. I guess the bigger question would be, which is better for the following scenario: I have #wrap inside a slideshow, #wrap is in slide 1, but when the user clicks on slide 2 or 3, "hits" or "firstdown" needs to be reset.... I think I'll figure it out, thanks again for your great insight!
Yea, I figured it out. I just make hits = 0 for every time a slide link is pressed.
|

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.