4

I have a DIV in my page that is scrollable, while no other elements on the page are. (The page layout is fixed with controls above and below the DIV itself.) I would like the arrow keys and page up/page down to scroll the DIV under all circumstances, but I cannot seem to do so unless the DIV actually has the focus. There are other input fields in other DIVs which often have focus. I have tried capturing the arrow keys and page/up down 'keydown' event at the document level and simulating the same event directly (using answers from this question) to the DIV that needs to scroll, but no scrolling occurs. I know the event is being dispatched because if I attach an event handler I see it, but for some reason it doesn't cause any scrolling. I have also tried setting the "tabIndex" attribute of the DIV with no difference.

How can I designate a specific element to receive specific keys like this? It is extremely user unfriendly to require a specific element to be focused for certain keys to work, when those keys only make sense for a single element on the page. Having to constantly switch focus from another element to the scrollable area to scroll and back to enter data just isn't acceptable.

I have seen suggestions that scrolling can be simulated by other means, but I want to avoid that route because this doesn't always produce identical results, and I also want to generalize it to other kinds of key events and action besides scrolling.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Michael
  • 9,060
  • 14
  • 61
  • 123

2 Answers2

6

You can scroll any element by adjusting its scrollTop DOM property.

If you capture all the keydown events on the document and then decide on what action you want to take depending on the key pressed (use the which property of the event object) and maybe some other circumstances (inputs focused, controls checked etc.) you can easily scroll your div. Check out this fiddle for a simple demo.

Tadeáš Peták
  • 567
  • 2
  • 13
0

you can you keypress or keyDown events on the document and trigger actions on your DIV.

$(document).ready(function(){


$(document).on("keydown", handleKeyDown);

 function handleKeyDown(evt) {

var code = parseInt(evt.keyCode); // the key Code of the key which was pressed during the event /and parses it and returns a 'integer'.


    if(code == 38){ // 38 is the keycode for UP key on the keyboard
    alert("up");
    } else if(code == 40) // 40 is the keycode for down key on the keyboard.
    alert("down");
    }
    }
  });

and as explained in breif by Tadeáš Peták you can use the scrollTop DOM property to scroll any element, enjoy.

Adarsh Hegde
  • 623
  • 2
  • 7
  • 19