0

When I try to search for this online I get results for people trying to programmatically scroll a webpage. That's not my mission. I have a website that I browse to and then try to use the keyboard up/down or page up/down arrows to scroll but it won't until I click in the main content pane (div.main-content) on the right.

My question is, what do I write in the JavaScript at the bottom of the page (or perhaps at the end of the jQuery document load event) to cause it to make that the scrolling div? I tried $('.main-content').focus(), but that didn't seem to work.

Jeremy Foster
  • 4,673
  • 3
  • 30
  • 49
  • Possible duplicate of [Enable div to scroll by keyboard without clicking](http://stackoverflow.com/questions/12410856/enable-div-to-scroll-by-keyboard-without-clicking) – Klinger Dec 08 '16 at 04:54

2 Answers2

1

Most browsers will not let you focus arbitrary elements, even scrollable ones. Try using the tabIndex attribute/property.

Here is an example that will set the tabIndex property/attribute to the default value if it is not already set.

var $mainContent = $('.main-content');
$mainContent.prop('tabIndex', $mainContent.prop('tabIndex'));
$mainContent.focus();
.main-content {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  overflow: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="main-content">
  <p>blah</p>
  <p>blah</p>
  <p>blah</p>
  <p>blah</p>
  <p>blah</p>
  <p>blah</p>
  <p>blah</p>
  <p>blah</p>
  <p>blah</p>
</div>
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • That did it, but I don't understand what `$mainContent.prop('tabIndex', $mainContent.prop('tabIndex'));` does. Why the recursion? – Jeremy Foster Dec 08 '16 at 07:01
  • @JeremyFoster It reads the current property value, and explicitly sets it on the element creating the attribute if it is not set. If the attribute was set explicitly, it doesn't change anything. If it was not set, it sets it to the default. You could substitute the second parameter with a specific value if you want, this just automatically uses the current computed value. – Alexander O'Mara Dec 08 '16 at 07:03
0

Divs can be focused if they have tabindex attribute.

Jquery docs:

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (input, select, etc.) and links (a href). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

So you can try this:

var used = false;
$(document).on('keydown', function(){ 
  if(!used){
    used = true;
    $('.main-content').attr("tabindex", -1).focus();
  }
 });
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37