Skip to content

Instantly share code, notes, and snippets.

@nfouka
Created July 21, 2018 15:40
Show Gist options
  • Save nfouka/8fd0e24428e0d5d954de69d8ee93de8d to your computer and use it in GitHub Desktop.
Save nfouka/8fd0e24428e0d5d954de69d8ee93de8d to your computer and use it in GitHub Desktop.
Basic Autocomplete
<div class="wrap">
<div class="lookup">
<label>lookup <input type="text" placeholder="a word" /></label>
<ul class="matches"></ul>
</div>
</div>
(function($) {
$.fn.autocomplete = function(words, output) {
var startsWith = function(letters) {
return function(word) {
return word.indexOf(letters) === 0;
}
}
var matches = function(letters) {
return letters ?
$.grep(words, startsWith(letters)) : [];
}
this.keyup(function() {
var letters = $(this).val();
output(letters, matches(letters));
});
};
})(jQuery);
var words = [
'random', 'list', 'of', 'words',
'draisine', 'swithe', 'overdiversification', 'bitingness',
'misestimation', 'mugger', 'fissirostral', 'oceanophyte',
'septic', 'angletwitch', 'brachiopod', 'autosome',
'uncredibility', 'epicyclical', 'causticize', 'tylotic',
'robustic', 'chawk', 'mortific', 'histotomy',
'slice', 'enjambment', 'mercaptids', 'oppositipetalous',
'impious', 'pollinivorous', 'poulaine', 'wholesaler'
];
var render = function($output) {
return function(letters, matches) {
$output.empty()
if(matches.length) {
var $highlight = $('<span/>')
.text(letters)
.addClass('highlight');
$.each(matches, function(index, match) {
var remaining = match.replace(letters, '');
$match = $('<li/>')
.append($highlight.clone(), remaining)
.addClass('match');
$output.append($match);
});
}
}
}
$(document).ready(function() {
$('input').autocomplete(words.sort(), render($('.matches')));
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
html, body {
width: 100%;
height: 100%;
}
.wrap {
width: 100%;
text-align: center;
}
.lookup {
margin: 1em 0;
padding: 1em;
background-color: #A1D9FF;
border-radius: 0.5em;
display: inline-block;
text-align: left;
}
.matches {
margin: 0.5em 0 0;
padding: 0;
}
.matches > .match {
margin: 0;
padding: 0.5em;
background-color: white;
list-style: none;
}
.matches > .match:first-child {
border-top-left-radius: 0.5em;
border-top-right-radius: 0.5em;
}
.matches > .match:last-child {
border-bottom-left-radius: 0.5em;
border-bottom-right-radius: 0.5em;
}
.match > .highlight {
background-color: #70CDFF;
border-radius: 0.2em;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment