niaomingjian niaomingjian - 9 days ago 5
Javascript Question

How to know which div should be scrolled?

In a web page, there are two scrollable divs.
When I press

Arrow down key
, one of these divs scrolls down.

How does the webpage know which div should be scrolled?

Is there a mark in this div which should be scrolled?

How to program to verify this?

In fact, I want to control this scroll behavior. When I press Arrow keys, I want to focus in the next item in the div instead of scrolling.

Answer

The other answers won't work if you don't set tabindex on divs.

Check here https://jsfiddle.net/Havock94/qb2hy8Lt/

Set tabindex on divs

<div id="one" tabindex="1">

Capture keydown and prevent the scroll

$('div').keydown(function(e) {
        e.preventDefault();

and then handle the keypress