htmlcsshtmx

Setting "focus" for scrolling items in HTML


I am not sure that "focus" is the right term here, but I don't know of anything better.

What I mean here by "focus" on a scrolling item is that the user can scroll that particular item with page-up and page-down keys. A container div on a page has a scrollbar, and I'd like it to have "focus" on load. Is there a way of doing that?


Solution

  • Focus is the exact term. It's used mostly for tab navigation and it is an accessibility feature. To implement it we should use tabindex.

    Note: tabindex="-1" may be useful for elements that should not be navigated to directly using the Tab key...

    Since the div should not be focused with the tab key but programmatically we are going to use tabindex="-1".

    Putting it together, you should be able to scroll the div using the arrow keys immediately:

    const scrollableDiv = document.getElementById("b");
    scrollableDiv.focus();
    .box {
      display: flex;
    }
    
    .scrollable {
      width: 200px;
      height: 200px;
      overflow: scroll;
      border: 1px solid #ccc;
    }
    
    .content {
        height: 500px;
    }
    <div class="box">
      <div class="scrollable"><div class="content">a</div></div>
      <div class="scrollable" id="b" tabindex="-1"><div class="content">b</div></div>
    </div>