-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch Bar.html
96 lines (84 loc) · 2.86 KB
/
Search Bar.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Bar with Autocomplete</title>
<style>
.search-container {
position: relative;
width: 300px;
max-width: 100%;
margin: 20px auto;
}
.search-input {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
}
.autocomplete-list {
position: absolute;
width: 100%;
background-color: #fff;
border: 1px solid #ccc;
border-top: none;
border-radius: 0 0 4px 4px;
max-height: 200px;
overflow-y: auto;
display: none;
}
.autocomplete-item {
padding: 10px;
cursor: pointer;
}
.autocomplete-item:hover {
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div class="search-container">
<input type="text" class="search-input" placeholder="Search...">
<div class="autocomplete-list"></div>
</div>
<script>
const searchInput = document.querySelector('.search-input');
const autocompleteList = document.querySelector('.autocomplete-list');
// Sample data for autocomplete suggestions
const suggestions = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape'];
searchInput.addEventListener('input', function() {
const inputValue = this.value.toLowerCase();
const matchedSuggestions = suggestions.filter(item =>
item.toLowerCase().startsWith(inputValue)
);
displaySuggestions(matchedSuggestions);
});
function displaySuggestions(items) {
if (items.length === 0) {
autocompleteList.style.display = 'none';
return;
}
autocompleteList.innerHTML = '';
items.forEach(item => {
const div = document.createElement('div');
div.textContent = item;
div.className = 'autocomplete-item';
div.addEventListener('click', function() {
searchInput.value = item;
autocompleteList.style.display = 'none';
});
autocompleteList.appendChild(div);
});
autocompleteList.style.display = 'block';
}
// Close the autocomplete list when clicking outside
document.addEventListener('click', function(e) {
if (!searchInput.contains(e.target) && !autocompleteList.contains(e.target)) {
autocompleteList.style.display = 'none';
}
});
</script>
</body>
</html>