Quillion
Quillion

Reputation: 6476

Focus on scroll section of html

I have a page consisting of three div sections.

<div id="header">
<!--header html goes here-->
</div>
<div id="body" class="page-body">
<!--main html goes here-->
</div>
<div id="footer">
<!--footer html goes here-->
</div>

and my css is

body {
    overflow: hidden;
}

.page-body
{
    overflow: auto;
}

The problem with this is if user pressed PgDn or down arrow key then the page doesn't scroll down. In order for page to scroll down through keyboard the user has to first click on page-body div section and then the key presses work.

I have tried using autofocus tag on the page-body div or writing document.getElementById('page-body').focus() on load, but nothing seems to work. How can I get keyboard to work as soon as page loads without having to click on the section? I would prefer solution without javascript since my page doesn't really need it, but if I have to I am ok with javascript solution too.

Upvotes: 2

Views: 2320

Answers (2)

Quillion
Quillion

Reputation: 6476

LattyS has provided valid code snippet and also valid js answer, however if you would like to get this done without using js then all you have to do is use tabindex attribute with autofocus attribute.

body {
  overflow: hidden;
}

.page-body {
  overflow: auto;
  max-height: 200px;
}
<div id="header">
  <!--header html goes here-->
  Header
</div>
<div id="body" class="page-body" tabIndex="1" autofocus>
  <p>123</p>
  <p>123 123</p>
  <p>123 123 123</p>
  <p>123 123 123 123</p>
  <p>123 123 123 123 123</p>
  <p>123 123 123 123</p>
  <p>123 123 123</p>
  <p>123 123</p>
  <p>123</p>
</div>
<div id="footer">
  <!--footer html goes here-->
  Footer
</div>

Upvotes: 1

LattyS
LattyS

Reputation: 160

You were almost there, just add a positive tabindex attribute on your div. But you should know that in term of accessibility it is not a very good practice.

window.onload = function() {
  document.getElementById('body').focus();
};
body {
  overflow: hidden;
}

.page-body {
  overflow: auto;
  max-height: 200px;
}
<div id="header">
  <!--header html goes here-->
</div>
<div id="body" class="page-body" tabIndex="1">
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
</div>
<div id="footer">
  <!--footer html goes here-->
</div>

Upvotes: 1

Related Questions