Skip to content

Commit

Permalink
Copied the scroll.js file from github/auto-complete-element.
Browse files Browse the repository at this point in the history
Scrolls to the target list element when navigating.
  • Loading branch information
bnjamin committed Jun 27, 2019
1 parent f2e3546 commit 5c0b27b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/combobox-nav.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* @flow strict */

import {scrollTo} from './scroll'

export function install(input: HTMLTextAreaElement | HTMLInputElement, list: HTMLElement): void {
input.addEventListener('compositionstart', trackComposition)
input.addEventListener('compositionend', trackComposition)
Expand Down Expand Up @@ -103,6 +105,7 @@ export function navigate(
if (target === el) {
input.setAttribute('aria-activedescendant', target.id)
target.setAttribute('aria-selected', 'true')
scrollTo(list, target)
} else {
el.setAttribute('aria-selected', 'false')
}
Expand Down
15 changes: 15 additions & 0 deletions src/scroll.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/* @flow strict */

export function scrollTo(container: HTMLElement, target: HTMLElement) {
if (!inViewport(container, target)) {
container.scrollTop = target.offsetTop
}
}

function inViewport(container: HTMLElement, element: HTMLElement): boolean {
const scrollTop = container.scrollTop
const containerBottom = scrollTop + container.clientHeight
const top = element.offsetTop
const bottom = top + element.clientHeight
return top >= scrollTop && bottom <= containerBottom
}

0 comments on commit 5c0b27b

Please sign in to comment.