Mateus Zitelli
Mateus Zitelli

Reputation: 1302

How to set scroll focus?

Let's suppose I have an HTML like this:

<body>
  <div id="header">
    header
  </div>
  <div id="container">
    <div id="large-content">
      large content
    </div>
  </div>
</body>

And CSS:

#container {
  max-height: 100px;
  overflow: auto;
}

#large-content {
  height: 500px;
}

How can I allow the user to scroll the container by pressing the arrow keys after he clicks on the #header?

I already tried .click() and .focus() on the #container without success. I can't find how Chrome manages the scroll focus.

Thanks for your help!

Upvotes: 0

Views: 218

Answers (1)

Davi
Davi

Reputation: 4147

Add a tabindex attribute to the #container element, then use .focus():

var headerEl = document.querySelector('#header'),
    scrollEl = document.querySelector('#container');
    
 headerEl.addEventListener('click', function () {
  scrollEl.focus();
 });
#container {
  max-height: 100px;
  overflow: auto;
}

#large-content {
  height: 500px;
}
<body>
  <div id="header">
    header
  </div>
  <div id="container" tabindex="0">
    <div id="large-content">
      large content
    </div>
  </div>
</body>

Upvotes: 2

Related Questions