blog/public/js/search.js
2025-08-20 15:19:24 +01:00

47 lines
1.2 KiB
JavaScript

document.addEventListener("DOMContentLoaded", function () {
let index = [];
// Load JSON index
fetch("/index.json")
.then((res) => res.json())
.then((data) => {
index = data;
console.log("Index loaded:", index.length, "posts");
})
.catch((err) => console.error("Error loading index.json", err));
const searchInput = document.getElementById("search");
const resultsList = document.getElementById("results");
function runSearch() {
const query = searchInput.value.trim().toLowerCase();
resultsList.innerHTML = "";
if (!query) {
return;
}
// filter out posts that don't match
const matches = index.filter(
(post) =>
post.content.toLowerCase().includes(query),
);
if (matches.length === 0) {
resultsList.innerHTML = "<li>You leafed too hard :/</li>";
return;
}
// Render matching posts
matches.forEach((post) => {
const li = document.createElement("li");
const link = document.createElement("a");
link.href = post.url;
link.textContent = post.title;
li.appendChild(link);
resultsList.appendChild(li);
});
}
searchInput.addEventListener("input", runSearch);
});