-
-
Save cssango/2a4fe2df7d15fa7d101aad215edfd982 to your computer and use it in GitHub Desktop.
Algolia autocomplete using custom source
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $(function () { | |
| var el = $('#search-query-input'); | |
| var cache = []; | |
| function search(query, callback) { | |
| /** Check if query has been already sent */ | |
| var stored = cache[query]; | |
| if (stored) { | |
| callback(JSON.parse(stored)); | |
| return; | |
| } | |
| /** No => search for it */ | |
| $.nette.ajax({ | |
| 'method': 'post', | |
| 'url': el.data('link'), | |
| 'data': { | |
| q: query | |
| }, | |
| 'success': function (payload) { | |
| var results = payload.places.concat(payload.clubs).concat(payload.girls); | |
| cache[query] = JSON.stringify(results); | |
| callback(results); | |
| } | |
| }); | |
| } | |
| autocomplete('#' + el.attr('id'), { | |
| autoselect: true, // Select 1st item × search on enter UX | |
| autoselectOnBlur: false, // On mobile devices = true @todo | |
| openOnFocus: true, | |
| keyboardShortcuts: ['s'], | |
| minLength: 2 | |
| }, [ | |
| { | |
| source: search, | |
| displayKey: function(suggestion) { | |
| return suggestion.name | |
| }, | |
| templates: { | |
| suggestion: function(suggestion) { | |
| return '<img src="' + suggestion.avatar + '" alt="Avatar" width="65" height="65">' + suggestion.name; | |
| }, | |
| empty: function() { | |
| return '<div class="not-found"><span>¯\\(ツ)/¯ Sorry, no results found...<span></div>'; | |
| } | |
| } | |
| } | |
| ]).on('autocomplete:selected', function(event, suggestion, dataset) { | |
| location.href = suggestion.link; | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment