Skip to content

Commit dfbb4ca

Browse files
committed
feat(search): Implement search debounce and GA event
Adds debounce to search input and Google Analytics event tracking.
1 parent 376dcad commit dfbb4ca

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

assets/js/search.js

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
let fuse;
1515
let searchData;
1616
let isFuseInitialized = false;
17+
let debounceTimer;
1718

1819
// Function to load a script dynamically
1920
function loadScript(src) {
@@ -124,19 +125,31 @@
124125

125126
if(searchInput) {
126127
searchInput.addEventListener('input', () => {
127-
if (!isFuseInitialized) {
128-
searchResults.innerHTML = '<div class="text-center text-gray-500 py-4">Initializing search...</div>';
129-
return;
130-
}
131-
const query = searchInput.value.trim();
132-
if (query.length < 2) {
133-
searchResults.innerHTML = '';
134-
if (searchPlaceholder) searchResults.appendChild(searchPlaceholder);
135-
return;
136-
}
128+
clearTimeout(debounceTimer);
129+
debounceTimer = setTimeout(() => {
130+
if (!isFuseInitialized) {
131+
searchResults.innerHTML = '<div class="text-center text-gray-500 py-4">Initializing search...</div>';
132+
return;
133+
}
134+
const query = searchInput.value.trim();
135+
if (query.length < 2) {
136+
searchResults.innerHTML = '';
137+
if (searchPlaceholder) searchResults.appendChild(searchPlaceholder);
138+
return;
139+
}
140+
141+
// --- Google Analytics Event Tracking ---
142+
if (typeof gtag === 'function') {
143+
gtag('event', 'search', {
144+
search_term: query
145+
});
146+
console.log(`GA Event sent: search, search_term: ${query}`);
147+
}
148+
// -----------------------------------------
137149

138-
const results = fuse.search(query, { limit: 20 });
139-
renderResults(results, query);
150+
const results = fuse.search(query, { limit: 20 });
151+
renderResults(results, query);
152+
}, 500); // Wait 500ms after user stops typing
140153
});
141154
}
142155

0 commit comments

Comments
 (0)