-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsearch.js
More file actions
56 lines (47 loc) · 1.53 KB
/
search.js
File metadata and controls
56 lines (47 loc) · 1.53 KB
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
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('search-input');
var results = document.getElementById('search-results');
var posts = [];
fetch('/search.json')
.then(function(response) { return response.json(); })
.then(function(data) {
posts = data;
if (window.location.hash) {
input.value = decodeURIComponent(window.location.hash.slice(1));
search();
}
});
function search() {
var query = input.value.toLowerCase().trim();
if (query.length < 2) {
results.innerHTML = '';
return;
}
var matches = posts.filter(function(post) {
return post.title.toLowerCase().includes(query) ||
post.excerpt.toLowerCase().includes(query) ||
post.tags.some(function(tag) { return tag.toLowerCase().includes(query); });
});
if (matches.length === 0) {
results.innerHTML = '<p>No results found.</p>';
return;
}
var html = '<ul class="post-list">';
matches.forEach(function(post) {
html += '<li>';
html += '<span class="post-meta">' + post.date + '</span> ';
html += '<a href="' + post.url + '">' + post.title + '</a>';
html += '</li>';
});
html += '</ul>';
results.innerHTML = html;
}
input.addEventListener('input', search);
document.querySelectorAll('.search-tag').forEach(function(tag) {
tag.addEventListener('click', function(e) {
e.preventDefault();
input.value = this.dataset.tag;
search();
});
});
});