Skip to content

Commit ec51f10

Browse files
author
Mike Lumetta
committed
Allow focus to remain on the targets of hash links when the element navigated to should be focusable:
1. natively focusable elements (a, input, textarea, select, button) 2. elements where the target had a tabindex prior to the navigation event This change allows consumers of react-router-hash-link to apply focus styles to the target element.
1 parent 0a4fb66 commit ec51f10

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/index.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ function reset() {
1616
}
1717
}
1818

19+
function isInteractiveElement(element) {
20+
const interactiveTags = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'];
21+
return interactiveTags.includes(element.tagName) && !element.hasAttribute('disabled');
22+
}
23+
1924
function getElAndScroll() {
2025
let element = null;
2126
if (hashFragment === '#') {
@@ -43,11 +48,16 @@ function getElAndScroll() {
4348
let originalTabIndex = element.getAttribute('tabindex');
4449
if (originalTabIndex === null) element.setAttribute('tabindex', -1);
4550
element.focus({ preventScroll: true });
46-
// for some reason calling blur() in safari resets the focus region to where it was previously,
47-
// if blur() is not called it works in safari, but then are stuck with default focus styles
48-
// on an element that otherwise might never had focus styles applied, so not an option
49-
element.blur();
50-
if (originalTabIndex === null) element.removeAttribute('tabindex');
51+
if (originalTabIndex === null) {
52+
if (!isInteractiveElement(element)) {
53+
// for some reason calling blur() in safari resets the focus region to where it was previously,
54+
// if blur() is not called it works in safari, but then are stuck with default focus styles
55+
// on an element that otherwise might never had focus styles applied, so not an option
56+
element.blur();
57+
}
58+
59+
element.removeAttribute('tabindex');
60+
}
5161

5262
reset();
5363
return true;

0 commit comments

Comments
 (0)