Skip to content

Commit 08fe773

Browse files
author
Vianpyro
committed
Implement search functionality in SearchBar component with debounce support
1 parent 77b1971 commit 08fe773

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/components/SearchBar.astro

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,34 @@ const { placeholder } = Astro.props;
4545
}
4646
}
4747
</style>
48+
49+
<script type="module" is:inline>
50+
let debounceTimeout;
51+
52+
function handleSearch(input) {
53+
const query = input.value.trim().toLowerCase();
54+
const products = document.querySelectorAll('.product-card');
55+
products.forEach(product => {
56+
const name = product.querySelector('h1')?.textContent.toLowerCase() || '';
57+
product.style.display = (query && name.includes(query)) ? 'flex' : (query ? 'none' : 'flex');
58+
});
59+
}
60+
61+
function initSearchBar() {
62+
const input = document.querySelector('.search-bar input');
63+
const button = document.querySelector('.search-bar button');
64+
65+
button.addEventListener('click', () => handleSearch(input));
66+
67+
input.addEventListener('input', () => {
68+
clearTimeout(debounceTimeout);
69+
debounceTimeout = setTimeout(() => handleSearch(input), 500);
70+
});
71+
}
72+
73+
if (document.readyState === 'loading') {
74+
document.addEventListener('DOMContentLoaded', initSearchBar);
75+
} else {
76+
initSearchBar();
77+
}
78+
</script>

0 commit comments

Comments
 (0)