iTranslated by AI
Accessibility: Ensuring Focus Moves When Implementing Smooth Scrolling with JavaScript
Recently, you may implement smooth scrolling using scroll-behavior, but when implementing it with JavaScript, you must verify that the focus has also moved to the destination element.
If the focus remains on the triggering element (such as an <a> or <button> tag) rather than moving to the target, keyboard users cannot reach the destination element, making the in-page link functionality itself unusable.
This issue occurs because JavaScript-based smooth scrolling uses event.preventDefault() to block the default behavior of tags like <a>. Since focus management is handled automatically when using only HTML and CSS, a custom implementation can inadvertently break a feature that would normally be available.
When Implementing with JavaScript
Here is an implementation example using a library called sweet-scroll.
import SweetScroll from 'sweet-scroll';
const scroller = new SweetScroll({
after(offset, $trigger, scrollElement) {
const destination = document.getElementById(scrollElement.ctx.hash.replace('#', ''));
destination.setAttribute('tabindex', '-1');
destination.focus();
},
});
- sweet-scroll provides callback functions (in this case,
after), which we use here. - Since
scrollElement.ctx.hashreturns a hash value like#foo, we use it to retrieve the destination element. - By setting
tabindexto-1, the element is excluded from the normal Tab order but can still be programmatically focused using JavaScript. -
.focus()moves the focus to the target destination element.
Discussion