How does `space` paging work in browsers?

Viewed 61

Imagine a page with two side-by-side <div> elements like https://nodejs.org/dist/latest-v12.x/docs/api/.

The <div> on the left navigates between pages. The one on the right has the actual content.

When I press space (spacebar), the browser advances the content of the right-hand <div> by one screenful, reminiscent of the traditional UNIX pager more. (IIRC, this has been fairly standard browser behavior since NCSA Mosaic.)

However, sometimes I want to scroll the column on the left (the "navigation" column). How does the browser decide which column to scroll when space is pressed? The document.activeElement is <body>, an ancestor of both of those column <div> elements. I want to be able to change the focus using a bookmarklet (or extension)—which I will be happy to write myself, but this mechanism seems not to be governed by HTMLElement.focus() in any way that I understand.

2 Answers

When pressing the space bar (or arrow keys, pg-down, pg-up, etc...), the browser scrolls the closest scrollable parent of the currently active element. When you open the page, the active element is <html> and that's the element that will be scrolled (if its scrollable) and it the flow content exceeds its height (which, by default, is viewport's height).

If the currently active element is the sidebar or one of its children, pressing space will scroll the sidebar, not the <html> element. You can change the active element through various methods (clicking, pressing tab, programmatically, etc...).

use tabIndex attribute for manipulate it with focus()

for xmpl with provided by you page:

document.getElementById("column2").tabIndex = 0;
document.getElementById("column1").tabIndex = 0;
document.addEventListener("keydown",function(){
    if(event.ctrlKey){
        if(document.activeElement.id=="column1")
            document.getElementById("column2").focus();
        else
            document.getElementById("column1").focus();
    }
});
Related