Skip to content

Instantly share code, notes, and snippets.

@bobylito
Last active June 24, 2016 13:22
Show Gist options
  • Save bobylito/76884d7261e6cc06d0d23b1bd0a11c96 to your computer and use it in GitHub Desktop.
Save bobylito/76884d7261e6cc06d0d23b1bd0a11c96 to your computer and use it in GitHub Desktop.

AlgoliaSearch Helper - getting started - step 3

In this sample, we cover those topics:

  • how to declare a facet in the configuration of the helper
  • how to display the facet values computed by the API
  • how to refine a facet

See on jsFiddle

#search-box {
margin: 1em 1em 3em;
width: calc(100% - 2em);
padding: 1em;
border: 1px solid #ccc;
border-radius: 2px;
box-sizing: border-box;
}
#facet-list,
#container{
max-width: 150px;
width: 100%;
float: left;
padding: 0 1em;
margin: 0;
list-style: none;
}
#facet-list li {
padding: 6px 0;
border-bottom: 1px solid #ccc;
}
#facet-list li input {
margin-right: 6px;
}
#container {
max-width: calc(100% - 150px - 4em);
}
#container li {
padding: 8px 0;
}
#container em {
background: yellow;
}
<input type="text" autocomplete="off" id="search-box"/>
<ul id=facet-list></ul>
<ul id=container></ul>
<script src="https://cdn.jsdelivr.net/g/algoliasearch@3(algoliasearchLite.min.js),algoliasearch.helper@2"></script>`
//Config
var applicationID = 'latency';
var apiKey = '249078a3d4337a8231f1665ec5a44966';
var index = 'bestbuy';
var client = algoliasearch(applicationID, apiKey);
var helper = algoliasearchHelper(client, index, {
facets: ['type']
});
helper.on('result', function(content) {
renderFacetList(content); // not implemented yet
renderHits(content);
});
function renderHits(content) {
$('#container').html('').append(function() {
return $.map(content.hits, function(hit) {
return $('<li>').html(hit._highlightResult.name.value);
});
});
}
$('#facet-list').on('click', function(e) {
var facetValue = $(e.target).data('facet');
if(!facetValue) return;
helper.toggleRefinement('type', facetValue)
.search();
});
function renderFacetList(content) {
$('#facet-list').html('').append(function() {
return $.map(content.getFacetValues('type'), function(facet) {
var checkbox = $('<input type=checkbox>')
.attr('data-facet', facet.name)
.attr('id', 'fl-' + facet.name);
if(facet.isRefined) checkbox.attr('checked', 'checked');
var label = $('<label>').html(facet.name + ' (' + facet.count + ')')
.attr('for', 'fl-' + facet.name);
return $('<li>').append(checkbox).append(label);
});
});
}
$('#search-box').on('keyup', function() {
helper.setQuery($(this).val())
.search();
});
helper.search();
name: Helper getting started / step 2
description: First search with the helper
authors:
- Algolia
resources:
- https://cdn.jsdelivr.net/algoliasearch/3.15.1/algoliasearchLite.min.js
- https://cdn.jsdelivr.net/algoliasearch.helper/2.10.0/algoliasearch.helper.min.js
normalize_css: yes
wrap: b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment