I'm trying to add a "load more" function to a "search" function which retrieves data from a JSON file. I found this javascript for Load More Content On Click Button:
const loadmore = document.querySelector('#loadmore');
let currentItems = 2;
loadmore.addEventListener('click', (e) => {
const elementList = [...document.querySelectorAll('.results-cntr .search-result')];
for (let i = currentItems; i < currentItems + 2; i++) {
if (elementList[i]) {
elementList[i].style.display = 'block';
}
}
currentItems += 2;
// Load more button will be hidden after list fully loaded
if (currentItems >= elementList.length) {
event.target.style.display = 'none';
}
})
and this is the css:
.search-result {
display: none;
}
.results-cntr .search-result:nth-child(1) {
display: block;
}
.results-cntr .search-result:nth-child(2) {
display: block;
}
Here's my search function which retrieves data from a JSON file:
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);
});
};
});
What I am trying to do is to integrate these together, Search and Load More Content On Click Button, but it is beyond my capabilities. Any help is much appreciated. Thanks.