Created
May 10, 2018 23:37
-
-
Save DanielHeath/3d5e64287f991aecdb8004a2bb1e0147 to your computer and use it in GitHub Desktop.
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
//= 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