10

This is similar to SO: how to move a div with arrow keys, so maybe a clear and informed 'no' suffices as an answer:

Can I make an overflowing div a "default scroll target" that reacts to arrow-up/down/page-down/space the same way as an overflowing document (i.e. scrolls down the content)? The page itself does not have a scrollbar (simple example below). In particular, can this be accomplished without explicitly tracking key events (neither directly nor hidded by a JS library)?

<html>
 <body>
  <div id="contentcontainer" style="height:200px;width:200px;overflow:scroll">
   <div id="innercontent" style="height:2000px;">foo</div>
  </div>
 </body>
</html>

Edit: Of course the above works after I click into the div. Basically, I want to avoid having to do that...

Community
  • 1
  • 1
dcn
  • 4,389
  • 2
  • 30
  • 39
  • have you thought about simply [styling the scrollbars](http://websitetips.com/articles/css/scrollbars/) of the div and enforcing some sort of focus on it – T I Jan 10 '12 at 15:19
  • yes but you still need to focus the div element. Why you dont just try, i went to a site and just clicked into the overflowing div, and used keys, no problem... but an "auto-focus" you will not be able to accomplish i think...7 – Luke Jan 10 '12 at 15:21
  • I don't care about the styling. "Enforcing some sort of focus" may be what I am looking for... ;) How would that work? – dcn Jan 10 '12 at 15:22
  • 1
    I don't know how styling the scrollbars will help with this problem... (and you should not style the scrollbars, it is unsupported microsoft css extension) – Didier Ghys Jan 10 '12 at 15:22
  • Styled scrollbars are supported in WebKit too, and it's a useful feature. I don't see any reason not to style them. – Carl Smith Apr 15 '13 at 16:17

2 Answers2

12

In order for an html element to be focusable, it must be reachable with the Tab key. This means you can call .focus() on a link or an input. Additionally, body elements are always focusable.

You need to make your div reachable with the Tab key. You can accomplish this by setting the tabindex property on it. If you do not actually want people to be able to tab into that div, you can set the tabindex to -1, which will prevent people from actually tabbing to it but will otherwise set the element up for tabbing and focus.

Source: http://help.dottoro.com/ljpkdpxb.php

dhasenan
  • 1,177
  • 7
  • 15
  • 1
    After ensuring the div had a tabindex attribute, and then calling div.focus(), it worked! Thanks! – Josh Nov 11 '16 at 17:44
-3

Browsers usually have this behavior built-in,

In order to use arrow keys to scroll down your div, you must have an element within focused.

Lookup http://api.jquery.com/focus/

Luc Laverdure
  • 1,398
  • 2
  • 19
  • 36
  • 3
    Even after doing a `.focus()` on a form element within a div, Google Chrome does not recognize the div as the target of arrow key scroll keystrokes. – Brandon Rhodes Jun 05 '12 at 13:06