0

So i got a page with different divs in it and I want to scroll down with the arrow down key to each one, for example

<div id="one">
<div id="two"> 
<div id="three"> 

i first tried this

   var scrolled = 0;
   $("body").keyup(function(e) {    
        if(e.keyCode == 40) {
            scrolled++; 
            $('body,html').animate({scrollTop: 895 * scrolled}, 700);
        }

but this isn't what i want because obviously it won't work correctly on a computer with a different dpi so I tried this

$(document).keydown(function(e) {
    e.stopPropagation();

    if (e.keyCode == 40) {
        e.preventDefault();
        $('body').animate({
            'scrollTop': $('#one').offset().top}, 800);
    }

but i don't know how I could use this code to get to the div with the id #2 ... So could someone help me do that ?

Thanks

Tuor75
  • 1
  • 1
  • **Don't include # in IDs**, they should just be `id="1"` which is **also not acceptable** because a number cannot come first in a class/id. As a result, use `id="one"...` instead. You still select it with jQuery and CSS by using the pound as a selector, aka `$(#one)` for jQuery – Zach Saucier Mar 31 '14 at 15:31
  • Also, there are a lot of questions on this already. You need to use [`scrollTo`](http://stackoverflow.com/questions/6677035/jquery-scroll-to-element) and keep track of which is visible. *Side note:* using a keyboard to navigate is bad practice, especially for mobile – Zach Saucier Mar 31 '14 at 15:35
  • jep sorry typed this fastly, i see there are some faults in it it just is an example because my code is a bit too long .. but why the scrollTo, that won't solve my problem ? – Tuor75 Mar 31 '14 at 15:43

0 Answers0