Skip to content

Instantly share code, notes, and snippets.

@tamaker
Last active July 5, 2020 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamaker/9898bfad6eabc8ae810e48ec0e6add3e to your computer and use it in GitHub Desktop.
Save tamaker/9898bfad6eabc8ae810e48ec0e6add3e to your computer and use it in GitHub Desktop.
Fuse.js search demo v1
<div id="wrapper">
<center>
<input type="text" id="inputField" style="width: 450px; margin: 40px; margin-bottom: 0px; padding: 20px; font-size: 1.4em; background-color: #EEE; border-radius: .4em; border: 2px solid #CCC;" placeholder="search for..." value=""><br>
<div class="statusText">
Type a search word above, fuse.js is used to find and score matches found in each P element below. <!-- <br><br><b>Question:</b> Why are some matches overlooked and NOT found? <br><br>For example...<br>
<ol>
<li>the word "demands" Works and finds all (2) matches.</li>
<li>the word "views" Works and finds all (2) matches.</li>
</ol> -->
<pre></pre>
</div>
</center>
<div id="inner">
<p>Salmon prosperously squid some greedily the oh preparatory and echidna some dolphin curtsied random this out newt overthrew dearly even lucidly fox successfully and this below that much inconsiderate a much jeez sheepishly insect baboon the against far oh while delicately a crud when.</p>
<p>Quit abominably and clung some less some mastodon winced one far beaver in much hardy mastodon condescendingly oh more some according horse gosh thus the far up skillful.</p>
<p>Supportively gave more solicitous much as out grabbed far some mounted guinea bat much and allegedly about this when alas less this and pertly turtle darn ahead came meant and but unlike subconscious barring and barked cheered and.</p>
<p>Proudly dauntlessly grimy sighed concisely far krill beat a querulous a immaculately far indirectly between much in this hey gnu far hardheadedly ritual some derisive continually forthrightly wholesome the cuddled excluding yet out beside impetuous constitutional dear hazy that hence fallibly wow mastodon.</p>
<p>Vindictive far hello mallard woolly scorpion made wow ouch more and boa more the more gosh on far remote nodded yikes and dear between audibly chameleon winced weasel abominable that chastely up wow lantern macaw hello and.</p>
<p>Some the constant longingly around yet faultily oyster depending because in swept and when eagle neurotic swelled much dear leapt under dear noble moaned splashed floated dear a that much the on and views.</p>
<p>Forwardly much fussy hence more nightingale panda until one less without much more some on this unlike maladroit firefly far bandicoot far smiled and covetously through favorable.</p>
<p>Groundhog hey greedy hummingbird inaudibly porpoise jeez beheld clapped much into overhung hello including militantly lobster some according sold studied irritable naked jealously cowardly panda less and mechanically insistent a unheedfully via well.</p>
<p>Far so goose the gosh dear inanimately alas scallop opposite considering meadowlark plentifully had far amid well hawk hello falcon wolverine the porcupine darn that beside cost undertook views.</p>
<p>Crud recast kindhearted hare amenable and much much the listless oh direly hello during more forgave and assiduously this far bestially one that one goldfish far amidst and darn horse and far cooperative outside stood much along beside frustrating bridled soggily as affecting.</p>
</div>
</div>
$(document).ready(function () {
// THE ARRAY OUR SEARCHABLE CONTENT WILL BE PUSHED TO
list = [];
// ITERATE THROUGH ALL THE P ELEMENTS AND PUSH THE JSON OBJECT
//WITH CONTENT AND IDX NUMBER TO THE ARRAY
$("#inner p").each(function (i, val) {
$(this).attr("id", "item-" + i);
newObj = { paraNum: i, paraText: $(val).text() };
list.push(newObj);
});
console.table( list );
// OPTIONS PASSED INTO FUSE.JS
const options = {
threshold: 1.0,
ignoreLocation: true,
includeScore: true,
includeMatches: true,
findAllMatches: true,
keys: ["paraText"]
};
var fuse = new Fuse(list, options);
var result;
function doSearch(searchVal) {
result = fuse.search(searchVal);
console.log(result);
runHighlighting($("#inputField").val(), result);
}
function runHighlighting(searchVal, highlightResults) {
$.each(highlightResults, function (i, val) {
//console.log(i + ' ' + searchVal + ' - match found in item ' + val.refIndex);
var substring = new RegExp(searchVal, "gi");
var original = $("p").eq(val.item.paraNum).html();
//console.log(original)
var newvers = original.replace(substring, (match) => {
return '<span class="highlight">' + match + "</span>";
});
$("p").eq(val.refIndex).empty();
$("p").eq(val.refIndex).html(newvers);
if ($("#inputField").val().length) {
$("pre").text(
$(".highlight").length +
' matches found for "' +
$("#inputField").val() +
'"'
);
} else {
$("pre").text("");
}
});
}
// WAIT FOR INPUT TO STOP BEFORE RUNNING THE SEARCH
var timer = null;
$("#inputField").keydown(function () {
clearTimeout(timer);
timer = setTimeout(doStuff, 1000);
});
function doStuff() {
$("span.highlight").removeClass("highlight");
//$('span.highlight').contents().unwrap();
//alert('do stuff');
doSearch($("#inputField").val());
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/6.4.0/fuse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
/*html { width: 100%; height: 100%; margin: 0px; padding: 0px; } body { width: 90%; height: 100%; margin: 0 auto; padding: 0px; }
#wrapper { border: 1px solid red; margin: 0; margin-top: 20px; padding: 0px; height: 90%; }
#inner { border: 1px solid black; margin: 5px; height: 98%; padding: 0px; }*/
body { font-family: arial, helvetica; }
#inner > p { border: 1px solid black; max-width: 600px; margin: 0 auto; margin-bottom: 40px; padding: 10px; }
.highlight { background-color: yellow; color: red; }
pre { display: block; color: yellow; }
.statusText { border: 1px solid gray; background-color: black; padding: 10px; text-align:left; color: white; width: 90%; max-width: 500px; margin: 20px; font-family: arial, helvetica, sans-serif; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment