|
4 | 4 | function openSearchPopover () {
|
5 | 5 | document.getElementById('search-background').style.display = 'block'
|
6 | 6 | document.getElementById('search').style.display = 'block'
|
| 7 | + // focus the textbox after popover appears |
7 | 8 | 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' |
10 | 17 | }
|
11 | 18 |
|
12 | 19 | // open the popover when clicking the magnifying glass search icon
|
13 | 20 | 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 | + } |
19 | 27 |
|
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 |
21 | 38 | document.addEventListener('keydown', function (event) {
|
22 | 39 | if (event.ctrlKey && event.key === 'k') {
|
23 | 40 | event.preventDefault() // prevent focussing the URL bar in the browser
|
24 | 41 | openSearchPopover()
|
25 | 42 | }
|
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 | + } |
35 | 46 | })
|
36 | 47 | })()
|
0 commit comments