Hexo: Instant Search

Steps to implement the instant search module on the frontpage of this site:

  1. Install hexo-generator-search, developed by a member on the Hexo core team, to generate search data in .xml or .json.
  2. Attach the barebone script below to your desired Hexo layout file.
  3. Apply tweaking and styling.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<section id="search">
<form>
<input type="text" id="search-input" placeholder="Search...">
</form>
<div id="search-result"></div>
<p class="search-no-result" style="display: block;">No results found.</p>
</section>

<script src="/lib/jquery/jquery.min.js"></script> <!-- https://code.jquery.com/jquery-3.4.1.min.js -->
<script src="/js/search.js"></script> <!-- https://github.com/wzpan/hexo-theme-freemind/blob/master/source/js/search.js -->
<script type="text/javascript">
$(function() {

var $inputArea = $("input#search-input");
var $resultArea = document.querySelector("div#search-result");

$inputArea.focus(function() {
var search_path = "search.xml";
var path = "/" + search_path;
searchFunc(path, 'search-input', 'search-result');
});

$inputArea.keydown(function(e) {
if (e.which == 13) {
e.preventDefault();
}
});

var observer = new MutationObserver(function(mutationsList, observer) {
if (mutationsList.length == 1) {
if (mutationsList[0].addedNodes.length) {
$(".search-no-result").hide();
} else if (mutationsList[0].removedNodes.length) {
$(".search-no-result").show(200);
}
}
});

observer.observe($resultArea, { childList: true });

});
</script>

  1. 潘伟洲. hexo-generator-search.
  2. 潘伟洲. hexo-theme-freemind.
  3. 廖雪峰. jQuery.