I'm using the instantsearch.js library provided by Algolia.
The behaviour I want is: if the visitor hasn't entered anything in the search box then no results are returned.
However, the Algolia documentation states that:
If no query parameter is set, the textual search will match with all the objects.
Is it possible to change this behaviour, while still using instantsearch.js?
Here is the code I currently have:
<script type="text/javascript" src="http://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script>
<script type="text/javascript">
window.onload = function ()
{
function getTemplate(templateName) {
return document.getElementById(templateName + '-template').innerHTML;
}
var search = instantsearch({
appId: '{{config["ALGOLIA_APPLICATION_ID"]}}',
apiKey: '{{config["ALGOLIA_API_KEY"]}}',
indexName: '{{config["ALGOLIA_INDEX_NAME"]}}',
urlSync: true
});
search.addWidget(
instantsearch.widgets.searchBox({
container: '#search-input'
})
);
search.addWidget(
instantsearch.widgets.hits({
container: '#hits-container',
hitsPerPage: 10,
templates: {
item: getTemplate('hit'),
empty: getTemplate('no-results')
}
})
);
search.start();
};
</script>
You could use the searchFunction
and check the underlying helper state
to check whether or not the query is empty. Based on that, you can show/hide the search results div.
var search = instantsearch({
[...],
searchFunction: function(helper) {
var homePage = $('.home-page');
var searchResults = $('.search-results');
if (helper.state.query === '') {
// empty query string -> hide the search results & abort the search
searchResults.hide();
homePage.show();
return;
}
// perform the regular search & display the search results
helper.search();
homePage.hide();
searchResults.show();
}
}
This is also documented on the official website.
@aseure's solution will result in the script return
ing upon clicking "x" in the input to clear the search query. The following achieves the goal without breaking anything:
const search = instantsearch({
/* other parameters */
searchFunction(helper) {
const container = document.querySelector('#results');
if (helper.state.query === '') {
container.style.display = 'none';
} else {
container.style.display = '';
}
helper.search();
}
});
The above example is taken from the documentation here: https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-display/js/#handling-empty-queries
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With