diff options
| author | Serghei Iakovlev <egrep@protonmail.ch> | 2022-07-17 23:17:54 +0200 |
|---|---|---|
| committer | Serghei Iakovlev <egrep@protonmail.ch> | 2022-07-17 23:17:54 +0200 |
| commit | 9820930a9dfaf2d8125e701df4476e6ecc295966 (patch) | |
| tree | 7bdb3de19f8f4473a01c99eb252b90a17b683875 /assets/js | |
| parent | 9b26aecc75ca2ee2b4298d1e49a8876552fee633 (diff) | |
| download | gohugo-theme-ed-9820930a9dfaf2d8125e701df4476e6ecc295966.tar.gz | |
Add ability to populate query from URI params
Diffstat (limited to 'assets/js')
| -rw-r--r-- | assets/js/search.js | 31 |
1 files changed, 27 insertions, 4 deletions
diff --git a/assets/js/search.js b/assets/js/search.js index 3c24501..f92d324 100644 --- a/assets/js/search.js +++ b/assets/js/search.js @@ -34,15 +34,17 @@ async function initSearchIndex() { pagesIndex.forEach((page) => this.add(page)); }); + document.dispatchEvent(new CustomEvent('indexed')); } catch (e) { console.log(e); // eslint-disable-line no-console } } -function handleSearchQuery(event) { - event.preventDefault(); +function handleSearchQuery(query = null) { + if (!query) { + query = document.getElementById('search').value.trim().toLowerCase(); + } - const query = document.getElementById('search').value.trim().toLowerCase(); if (!query) { hideSearchResults(); return; @@ -302,6 +304,14 @@ if (!String.prototype.matchAll) { }; } +function getQueryParam(key) { + const params = new Proxy(new URLSearchParams(window.location.search), { + get: (searchParams, prop) => searchParams.get(prop) + }); + + return params[key]; +} + initSearchIndex(); document.addEventListener('DOMContentLoaded', function () { const searchForm = document.getElementById('search-form'); @@ -315,10 +325,23 @@ document.addEventListener('DOMContentLoaded', function () { e.preventDefault(); }); - searchInput.addEventListener('keyup', (e) => handleSearchQuery(e)); + searchInput.addEventListener('keyup', (e) => { + e.preventDefault(); + handleSearchQuery(null); + }); + searchInput.addEventListener('input', (e) => { if (!e.currentTarget.value) { hideSearchResults(); } }); }); + +document.addEventListener('indexed', () => { + const query = getQueryParam('q'); + + if (query) { + document.getElementById('search').value = query; + handleSearchQuery(query); + } +}); |
