medihack
medihack

Reputation: 16627

Find out which scroll element has keyboard focus

When having multiple elements with a scrollbar on one page (maybe by setting CSS overflow-scroll) the arrow keys on the keyboard do always only scroll one area (which is a good thing). It seems that always the last element with scrollbars I clicked on with the mouse recognizes the key events and scroll (example on Codepen).

Is there a way to find out which element (a div element in the above example) has keyboard "focus" (quotes as it doesn't seem to get a focus pseudoclass, see example above)?

Upvotes: 2

Views: 805

Answers (2)

Gezzasa
Gezzasa

Reputation: 1453

You can add tabindex="0" to the div.

https://codepen.io/gezzasa/pen/QrOdqX

Upvotes: 2

Kushtrim
Kushtrim

Reputation: 1939

You could add tabindex to your outer or scroll elements and then use document.activeElement

window.addEventListener('keydown', e => {
  let a = document.activeElement;
  console.log(a);
})
.container {
  display: flex;
}
.outer-left {
  width: 200px;
  height: 200px;
  overflow-y: scroll;
}

.inner-left {
  height: 500px;
  background-color: red;
}

.outer-right {
  width: 200px;
  height: 200px;
  overflow-y: scroll;
}

.inner-right {
  height: 500px;
  background-color: blue;
}
<div class="container">
  <div class="outer-left" tabindex="1">
    <div class="inner-left">
    </div>
  </div>
  <div class="outer-right" tabindex="2">
    <div class="inner-right">
    </div>
  </div>
</div>

Upvotes: 3

Related Questions