Question

I am using jQuery's scrollTo plugin to scroll up and down my page, using UP arrow and DOWN arrow.

i have a bunch of div with class "screen", as so: <div class="screen-wrapper">...</div>

What I am trying to do is, when i press UP or DOWN, the window scrolls to the next, or previous div with class of "screen".

I have the keypresses taken care of. According to the plugin docs, to scroll a window, you use $.scrollTo(...);

Here's the code I have:

$(document).keypress(function(e){
    switch (e.keyCode) {
        case 40:    // down
            n = $('.screen-wrapper').next()
            $.scrollTo( n, 800 );
          break;
        case 38:    // up

          break;
        case 37:    // left

          break;
        case 39:    // right

          break;

    }      
});

And if it helps, here's the HTML div. I have a few of these on the page, and essentially, am trying to scroll to next one by pressing down arrow:

<div class='screen-wrapper'>
<div class='screen'>
    <div class="sections">
        <ul>
            <li><img src="images/portfolio/sushii-1.png " /></li>
            <li><img src="images/portfolio/sushii-2.png" /></li>
            <li><img src="images/portfolio/sushii-3.png" /></li>
        </ul>
    </div>

    <div class="next"></div>
    <div class="prev"></div>
</div> 

And also if it needed, I can provide a link where this is being used if it'll help someone get a better idea.

edit And, i forgot to mention what the real question here is. The question/problem is that it won't scroll down past the first element, as seth mentioned.

Was it helpful?

Solution

There's no real question here but I'm going to guess the problem is that your page doesn't scroll past the first one. It's because you call this on every keypress:

            n = $('.screen-wrapper').next()

It's probably returning the same one every single time you call it. Try moving the instantiation outside of the keypress.

          var s = $('.screen');
          var curr=-1, node;

          $(document).keypress(function(e){
             switch( e.keyCode ) {
               case 40:
                  node = s[++curr];
                  if (node) {
                    $.scrollTo( node,800);
                  }
                  else {
                    curr = s.length-1;
                  }
                  break;
                case 38:
                   node = s[--curr];
                   if (node) {
                     $.scrollTo( node ,800);
                   }
                   else {
                      curr = 0;
                    }
                   break;
                }
          });

OTHER TIPS

I just implemented something similar and I used id attributes for each element.

Why not do something like

window.location.href = '#section-' + curr;

instead of using scrollTo?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top