react-scroll
react-scroll copied to clipboard
Scrolling to element fails to adjust the focus for accessibility
When I use the Link element in my header to smooth scroll to elements on my page, and then press tab to tab through that new section, the page jumps back to the header to focus on the next Link element. Is there a way to change the focus to the elements in the section I smooth scroll to so keyboard-only users don't get sent back to the top? Thanks!
Ran in to this also. Would be nice if react-scroll could handle this.
In the meantime adding tabindex
attribute to the element you want to scroll to:
<div id='comments' className='Comments' tabIndex='0'>
Allows you to use .focus()
to move the tab focus to it:
scrollToComments (e) {
e.preventDefault()
const commentsElem = document.getElementById('comments')
scroller.scrollTo('comments', {
smooth: true
})
commentsElem.focus()
}
Was this issue ever addressed? We have the same use case that we are tying to solve for. Thanks.
I have the same issue - it has negative implications for a11y so really wanting a fix for it. Thanks :)
It has not been fixed, any PR solving this is welcomed :)
Meanwhile @AlecRust has a workaround! :)
I've had a similar issue and solved this by managing the focus in the scroll-end event handler:
import { Events, ... } from "react-scroll";
...
useEffect(() => {
// After scrolling to target section, try to send focus to first interactive
// element (happens to be a <summary> in this app)
Events.scrollEvent.register("end", (_to, element) => {
element?.querySelector("summary")?.focus();
});
}, []);
I've also played around with resetting the focus to the document – (document.activeElement as HTMLAnchorElement).blur();
– however, I believe that is a worse practice a11y wise, as moving the focus to the targeted content does make sense.