Skip to content

Instantly share code, notes, and snippets.

@aaroneaton
Last active August 29, 2015 14:22
Show Gist options
  • Save aaroneaton/66c0951be2dd65e1f13c to your computer and use it in GitHub Desktop.
Save aaroneaton/66c0951be2dd65e1f13c to your computer and use it in GitHub Desktop.
Real-time support documentation search
var docs = om_docs.docs; // Loaded via wp_localize_script()
/*
Sample docs array
[
{
title: 'A post title',
url: 'http://optinmonster.com/docs/a-post-title'
}
]
*/
var fuseSearch = new Fuse(docs, {keys: ['title']}) // You can specify the object properties to search
// Yep. That's it.
// Run the search when the user types
$(document).on('keyup', '#doc-search-field', function() {
var $this = $(this),
searchTerm = $this.val();
// Run everything through the throttle method.
_.throttle( function() {
// Change the section header to match the search term
$('#search-header').text('Searching for "' + searchTerm + '"');
// Run Fuse search and build data object
var data = {
results: fuseSearch.search(searchTerm)
};
// Now display the results
var listTemplate = _.template($('script#tmpl-om-doc-results').html(), data);
$('#search-result-list').html(listTemplate);
}, 1000); // Only update every second
});
$(document).on('click', '.search-wrap .search-submit', function(e) {
var $this = $(this);
searchTerm = $('#doc-search-field').val();
e.preventDefault();
// Add the query argument to the URL
var href = $this.attr('href') + '?doc_search_term=' + term
// Now we can go to the ticket submission page
window.location.href = href;
});
<script type="text/html" id="tmpl-om-doc-results">
<% _.each(results, function(result) { %>
<li><a href="<%= result.url %>"><i class="fa-li fa fa-file-o"></i> <%= result.title %></a></li>
<% }); %>
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment