Skip to content

Commit 94d09d2

Browse files
Implement search input focus (#1417)
1 parent 9724e62 commit 94d09d2

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/components/Search/index.tsx

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,23 @@ const Search = ({ searchID }: { searchID?: string }): JSX.Element => {
2727
useEffect(() => {
2828
runDocsearchIfPossible()
2929

30+
const handleSearchTrigger = (event: KeyboardEvent) => {
31+
const slashKeyPressed = event.key === "/" || event.code === "Slash"
32+
if (!slashKeyPressed) {
33+
return
34+
}
35+
event.preventDefault()
36+
const searchInput = document.querySelector<HTMLInputElement>(
37+
`#${searchInputID}`
38+
)
39+
40+
if (searchInput) {
41+
searchInput.focus()
42+
}
43+
}
44+
45+
window.addEventListener("keypress", handleSearchTrigger)
46+
3047
if (document.getElementById("algolia-search")) return
3148

3249
const searchScript = document.createElement("script")
@@ -49,6 +66,10 @@ const Search = ({ searchID }: { searchID?: string }): JSX.Element => {
4966
}
5067

5168
document.body.appendChild(searchScript)
69+
70+
return () => {
71+
window.removeEventListener("keypress", handleSearchTrigger)
72+
}
5273
}, [])
5374

5475
return (

0 commit comments

Comments
 (0)