Is there a method for paging the results of a search?
rocc-o opened this issue · comments
rocc-o commented
I'm using a JavaScript search which fetch a JSON with data - the JSON is created in site root ./ and not in _data folder.
As the search results is a very long list I'd like to use pagination, but this is not a collection. Is there a method for paging the results of a search?
./assets/search.js
document.addEventListener('DOMContentLoaded', function(event) {
const btn = document.getElementById('theButton');
const results = document.getElementById('results');
let data = [];
let search_term = '';
fetch('/search.json')
.then(response => response.json())
.then(data_server => {
data = data_server;
});
btn.addEventListener('click', event => { search_term = search.value.toLowerCase();
showList();
});
const showList = () => {
results.innerHTML = '';
if (search_term.length <= 0) return;
const match = new RegExp(`${search_term}`, 'gi');
let result = data.filter(name => match.test(name.meta_title) || match.test(name.meta_description));
if (result.length == 0) {
const div = document.createElement('div');
div.innerHTML = `No results found`;
results.appendChild(div);
}
result.forEach(e => {
const div = document.createElement('div');
div.innerHTML = `<div class="search-result">
<a href="${e.url}"><h3 class="search-title">${e.meta_title}</h3></a>
<p class="search-description">${e.meta_description}</p>
<a href="${e.url}"><p class="search-url">› ${e.url}</p></a>
</div>`;
results.appendChild(div);
});
};
});
./search/index.njk
---
eleventyExcludeFromCollections: true
layout: _search-layout.njk
---
{% block content %}
<input aria-label="Search" type="search" id="search">
<button type="submit" id="theButton" aria-label="Search">Search</button>
<div id="results"></div>
{% endblock %}