Custom widgets from scratch
Using the raw widget API of InstantSearch.js v2 to create a minimalist implementation of a search UI
by bobylito
HTML
<script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2/dist/instantsearch.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2/dist/instantsearch.min.css">
<h3>
<a href="https://github.com/algolia/instantsearch.js/v2/guides/custom-widget.html">instantsearch.js</a> custom widget example
</h3>
<label>search:
<input id="searchBox" />
</label>
<h2>
Movies
</h2>
<div id="hits"></div>
CSS
*{ font-family: helvetica, arial; }
em {
color: #099;
font-style: normal;
text-decoration: underline;
}
JavaScript
const search = instantsearch({
appId: 'latency',
apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
indexName: 'movies',
});
search.addWidget({
init: function(opts) {
const helper = opts.helper;
const input = document.querySelector('#searchBox');
input.addEventListener('input', function(e) {
helper.setQuery(e.currentTarget.value) // update the parameters
.search(); // launch the query
});
}
});
search.addWidget({
render: function(opts) {
const results = opts.results;
// read the hits from the results and transform them into HTML.
document.querySelector('#hits').innerHTML = results.hits.map(function(h) {
return '<p>' + h._highlightResult.title.value + '</p>';
}).join('');
}
});
search.start();