2

I am trying to make a site scroll up when the left arrow is pressed, and down when the right arrow is pressed.

I am trying this:

    $("body").keydown(function(e){
        console.log( e.which );
        // left arrow
        if ((e.keyCode || e.which) == 37)
        {   
            e.keyCode = 38;
            e.which = 38;
            $("body").trigger( e );
        }
        // right arrow
        if ((e.keyCode || e.which) == 39)
        {
            e.keyCode = 40;
            e.which = 40;
            $("body").trigger( e );     
        }   
    });

But is not working fine, can you point me in the right direction?

Hey Hey
  • 83
  • 8

1 Answers1

1

Try controlling scroll instead of trying to trigger up and drow arrow. See below,

Below code actually scrolls by page, Change the $(window).height() to a fixed desirable value. (DEMO: http://jsfiddle.net/v5DZ9/1/)

//This is for page scroll. Use a reduced height instead of $(window).height() 
//for controlled scroll.
$(document).keyup(function (e) {
    if (e.which == 39) {
       window.scrollTo(0, $(window).height() + $(document).scrollTop()); 
    } else if (e.which == 37) {          
       window.scrollTo(0, $(document).scrollTop() - $(window).height());
    }
});

DEMO: http://jsfiddle.net/v5DZ9/

Note: Use it with caution, this code is untested.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • Thank you! This is actually very clever and helpful. I'm still curious how to trigger the event, I tried other methods and still no luck. – Hey Hey Mar 01 '13 at 21:54
  • @Jorge The keyCode property is a READ-ONLY property in event object. See http://stackoverflow.com/a/8776673/297641 for more details. – Selvakumar Arumugam Mar 01 '13 at 21:57
  • @Jorge If this answer is satisfying, don't forget to click on the green check mark on left to my answer to mark this question as answered. Also you can upvote if you think this is useful. :) – Selvakumar Arumugam Mar 01 '13 at 21:59