Skip to content

Instantly share code, notes, and snippets.

@DanielHeath
Created May 10, 2018 23:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielHeath/3d5e64287f991aecdb8004a2bb1e0147 to your computer and use it in GitHub Desktop.
Save DanielHeath/3d5e64287f991aecdb8004a2bb1e0147 to your computer and use it in GitHub Desktop.
//= require jquery
//= require lodash
$(function() {
var input = $('#searchInput'),
loader = $('#loader'),
searchInputTarget = $('#searchTarget'),
value = input.val();
if (!input.length)
return null; // did not find a searchInput, do nothing.
var latestSearchRequest; // We'll ignore responses which aren't to the most recent request
function inputChange() {
if (value != input.val()) { // input has changed
value = input.val();
history.pushState(
{},
"search for " + encodeURIComponent(value), // title
"?q=" + encodeURIComponent(value)
);
searchInputTarget.empty();
loader.show();
var req = $.get(
input.data('url') + "?term=" + encodeURIComponent(value) // should probably use this URL for replaceState too
)
latestSearchRequest = req;
req.then(function gotSearchResults(data) {
if (req === latestSearchRequest) {
loader.hide();
searchInputTarget.html(data)
}
})
}
}
input.on(
'propertychange change click keyup input paste',
_.debounce(inputChange, 250)
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment