Skip to content

Commit 35cfa7f

Browse files
fix: move focus to main content when skip-to-content is clicked (#665)
1 parent 342bcde commit 35cfa7f

4 files changed

Lines changed: 36 additions & 4 deletions

File tree

src/components/Header.astro

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,38 @@ const isActive = (path: string) => {
189189
});
190190
}
191191

192-
toggleNav();
192+
function handleSkipToContent() {
193+
const skipLink = document.getElementById("skip-to-content");
194+
if (!skipLink) return;
195+
skipLink.addEventListener("click", e => {
196+
if (
197+
e.defaultPrevented ||
198+
e.metaKey ||
199+
e.ctrlKey ||
200+
e.shiftKey ||
201+
e.button !== 0
202+
)
203+
return;
204+
e.preventDefault();
205+
const target = document.getElementById("main-content");
206+
if (target) {
207+
target.setAttribute("tabindex", "-1");
208+
target.addEventListener(
209+
"blur",
210+
() => target.removeAttribute("tabindex"),
211+
{
212+
once: true,
213+
}
214+
);
215+
target.focus();
216+
target.scrollIntoView({ behavior: "smooth" });
217+
}
218+
});
219+
}
193220

221+
toggleNav();
194222
document.addEventListener("astro:after-swap", toggleNav);
223+
224+
handleSkipToContent();
225+
document.addEventListener("astro:after-swap", handleSkipToContent);
195226
</script>

src/pages/404.astro

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const t = useTranslations(locale);
1616

1717
<main
1818
id="main-content"
19-
class="app-layout flex flex-1 items-center justify-center"
19+
class="app-layout my-1 flex flex-1 items-center justify-center"
2020
>
2121
<div class="mb-14 flex flex-col items-center justify-center">
2222
<h1 class="text-accent text-9xl font-bold">404</h1>

src/pages/index.astro

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ const homePath = getRelativeLocaleUrl(locale, "");
3131
id="main-content"
3232
data-layout="index"
3333
data-home-path={homePath}
34-
class="app-layout"
34+
class="app-layout my-1"
3535
>
3636
<section id="hero" class="border-border border-b pt-8 pb-6">
3737
<h1 class="my-4 inline-block text-4xl font-bold sm:my-8 sm:text-5xl">

src/styles/global.css

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
scrollbar-color: var(--color-muted) transparent;
1313
}
1414
a,
15-
button {
15+
button,
16+
#main-content {
1617
@apply outline-accent outline-offset-1 focus-visible:no-underline focus-visible:outline-2 focus-visible:outline-dashed;
1718
}
1819
button:not(:disabled),

0 commit comments

Comments
 (0)