Implementing a live search feature in a Jekyll website can significantly enhance user experience by allowing visitors to quickly find content without reloading the page. Using JavaScript, you can create a dynamic search that updates results in real-time as users type their queries. This guide will walk you through the steps to add a simple live search to your Jekyll site.
Prerequisites
- A Jekyll website with content to search through
- Basic knowledge of HTML, JavaScript, and Liquid templating
- Access to your site's code files
Step 1: Prepare Your Content Data
First, you need to create a JSON data file that contains the searchable content. You can generate this dynamically using a Jekyll plugin or manually. For simplicity, we'll assume you have a file named search.json in your site's root or assets folder, structured like this:
{
"posts": [
{"title": "First Post", "url": "/first-post", "content": "This is the first post content."},
{"title": "Second Post", "url": "/second-post", "content": "Details about the second post."}
]
}
Step 2: Add Search HTML Elements
Next, add a search input and a container for search results to your HTML layout, such as in your default.html layout or a specific page:
<input type="text" id="search-input" placeholder="Search..."/>
<div id="search-results"></div>
Step 3: Implement the JavaScript Search Functionality
Now, add JavaScript to fetch the JSON data and filter results based on user input. You can include this script at the bottom of your page or in a separate JS file:
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('search-input');
const resultsContainer = document.getElementById('search-results');
let data = [];
fetch('/search.json')
.then(response => response.json())
.then(json => {
data = json.posts;
});
searchInput.addEventListener('input', function() {
const query = this.value.toLowerCase();
resultsContainer.innerHTML = '';
if (query.length === 0) {
return;
}
const filteredResults = data.filter(post =>
post.title.toLowerCase().includes(query) ||
post.content.toLowerCase().includes(query)
);
if (filteredResults.length === 0) {
resultsContainer.innerHTML = 'No results found.
';
return;
}
filteredResults.forEach(post => {
const resultItem = document.createElement('div');
resultItem.innerHTML = `${post.title}`;
resultsContainer.appendChild(resultItem);
});
});
});
Conclusion
Adding a live search feature in Jekyll with JavaScript is straightforward and improves navigation for your visitors. Remember to update your search.json regularly to keep search results accurate. With this setup, your static site can provide a dynamic, app-like search experience.