Skip to content

Commit 6b509b0

Browse files
author
Felix Hennig
committed
feat: Add ESC keyboard handler
1 parent 57c528f commit 6b509b0

File tree

1 file changed

+28
-17
lines changed

1 file changed

+28
-17
lines changed

src/js/07-search.js

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,44 @@
44
function openSearchPopover () {
55
document.getElementById('search-background').style.display = 'block'
66
document.getElementById('search').style.display = 'block'
7+
// focus the textbox after popover appears
78
var searchInput = document.querySelector('.pagefind-modular-input')
8-
if (!searchInput) return
9-
searchInput.focus()
9+
if (searchInput) {
10+
searchInput.focus()
11+
}
12+
}
13+
14+
function closeSearchPopover () {
15+
document.getElementById('search-background').style.display = 'none'
16+
document.getElementById('search').style.display = 'none'
1017
}
1118

1219
// open the popover when clicking the magnifying glass search icon
1320
var searchButton = document.getElementById('search-button')
14-
if (!searchButton) return
15-
searchButton.addEventListener('click', function (event) {
16-
event.stopPropagation()
17-
openSearchPopover()
18-
})
21+
if (searchButton) {
22+
searchButton.addEventListener('click', function (event) {
23+
event.stopPropagation()
24+
openSearchPopover()
25+
})
26+
}
1927

20-
// open the popover with ctrl+k
28+
// close functionality when clicking the background
29+
var searchBackground = document.getElementById('search-background')
30+
if (searchBackground) {
31+
searchBackground.addEventListener('click', function (e) {
32+
e.stopPropagation() // trap event
33+
closeSearchPopover()
34+
})
35+
}
36+
37+
// open/close with keyboard
2138
document.addEventListener('keydown', function (event) {
2239
if (event.ctrlKey && event.key === 'k') {
2340
event.preventDefault() // prevent focussing the URL bar in the browser
2441
openSearchPopover()
2542
}
26-
})
27-
28-
// close functionality when clicking the background
29-
var searchBackground = document.getElementById('search-background')
30-
if (!searchBackground) return
31-
searchBackground.addEventListener('click', function (e) {
32-
e.stopPropagation() // trap event
33-
document.getElementById('search-background').style.display = 'none'
34-
document.getElementById('search').style.display = 'none'
43+
if (event.key === 'Escape') {
44+
closeSearchPopover()
45+
}
3546
})
3647
})()

0 commit comments

Comments
 (0)