Last active
August 29, 2015 14:07
-
-
Save noahbass/1757b13da41395721ea0 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
var index = lunr(function() { | |
this.field('title', { | |
boost: 10 | |
}) | |
this.field('body') | |
this.ref('id') | |
}); | |
{% for post in site.posts %} | |
index.add({ | |
id: {{ post.date | date: "%Y%m%d" }}, | |
title: {{ post.title | jsonify }}, | |
body: {{ post.description | jsonify }} | |
}); | |
{% endfor %} | |
var posts = []; | |
for(var key in index.documentStore.store) { | |
posts.push(key); | |
}; | |
function staticSearch(input) { | |
// set display: block; to all of the posts | |
posts.forEach(function(post) { | |
document.getElementById(post).style.display = 'block'; | |
}); | |
// get the results and set the matches to zero | |
var results = index.search(input.value), | |
matches = []; | |
results.forEach(function(result) { | |
// get the ids of the posts that match the search and place them in the 'matches' array | |
matches.push(result.ref); | |
}); | |
posts.forEach(function(post) { | |
// set display: none; to all of the posts | |
document.getElementById(post).style.display = 'none'; | |
}); | |
if(matches.length === 0) { | |
// no matches to the search | |
document.getElementById('search-value').innerHTML = input.value; | |
document.getElementById('search-no-results').style.display = 'block'; | |
} | |
else { | |
// set display: block; to all of the matches | |
matches.forEach(function(match) { | |
document.getElementById(match).style.display = 'block'; | |
}); | |
// hide the no-results box | |
document.getElementById('search-no-results').style.display = 'none'; | |
} | |
}; | |
function staticSearchReset() { | |
posts.forEach(function(post) { | |
// set display: block; to all of the posts | |
document.getElementById(post).style.display = 'block'; | |
}); | |
// hide the no-results box | |
document.getElementById('search-no-results').style.display = 'none'; | |
}; | |
var input = document.getElementById('search__input'); | |
window.onkeydown = function(event) { | |
if(input.value.length === 1 || input.value.length === 0) { | |
// there is no input | |
staticSearchReset(); | |
if(event.keyCode === 8 || event.keyCode === 46) { | |
input.blur(); | |
} | |
} | |
else { | |
// there is an input, do search | |
staticSearch(input); | |
} | |
if(event.keyCode === 27) { | |
input.blur(); | |
} | |
else { | |
input.focus(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment