Skip to content

Instantly share code, notes, and snippets.

@adamliptrot-oc
Created June 15, 2023 10:33
Show Gist options
  • Save adamliptrot-oc/cbf5dc7b42aaeebb2fb595ab4b92aefb to your computer and use it in GitHub Desktop.
Save adamliptrot-oc/cbf5dc7b42aaeebb2fb595ab4b92aefb to your computer and use it in GitHub Desktop.
// When using a link as a button with the aria role we need to handle the spacebar as this can be used for buttons but will scroll the page when used on non-native buttons
// Simply adding an eventlistener for the keypress event (which is what triggers the scroll) is not sufficient
// Native buttons allow a use to press the spacebar and then cancel it with the tab key
// So we need to listen for two events:
// 1. the keypress to cancel the scroll
// 2. the keyup to check the press has not been cancelled by a tabkey press - only this event results in a click being triggered
[].slice.call(document.querySelectorAll('a[role="button"]')).forEach(function (el) {
el.addEventListener('keypress', function (e) {
if (e.keyCode === 32) {
e.preventDefault();
}
})
el.addEventListener('keyup', function (e) {
if (e.keyCode === 32) {
e.preventDefault();
el.click();
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment