FAQ Search - Handlebars Renderer
by Ben Clayton
HTML
<script src="//flowcms.infxsolutions.com/script/handlebars.js/handlebars-v3.0.3.js"></script>
<input class="search" />
<div class="results"></div>
<div class="ids"></div>
<script id="faq" type="text/html">
{{#each .}}
<div class="result {{mcls}}">
<div>{{question}}</div>
<div class="small">{{answer}}</div>
Score:{{score}}
</div>
{{/each}}
</script>
CSS
.results {
margin-top: 30px;
position: relative;
}
.result {
position: relative;
border: 1px solid red;
width: 200px;
height: 80px;
display: inline-block;
margin: 4px;
background-color: #FFFFD0;
position: relative;
opacity: 1;
z-index: 2;
overflow: hidden;
padding: 3px;
}
.result.nomatch {
display: none;
}
.result.trans {
WebkitTransition: all 1s ease-in-out;
MozTransition: all 1s ease-in-out;
MsTransition: all 1s ease-in-out;
OTransition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
.result.hidden {
z-index: 2;
width: 10px;
height: 15px;
font-size: 2px;
}
.small {
font-size: 0.8rem;
}
JavaScript
var faqs = [{
question: "What colour is a carrot",
answer: "carrots are coloured red"
}, {
question: "What size is a flee",
answer: "flees are usually very small indeed"
}, {
question: "What car do you drive",
answer: "I drive a red ferrari"
}, {
question: "Does a motor bike sidecar off balence you",
answer: "Yes you also get power steer"
}, {
question: "are cork stopper best",
answer: "no they can flavour the wine"
}, {
question: "are plastic stopper favourite",
answer: "no they cheapen the wine"
}, {
question: "Sid Clayton",
answer: "[email protected]"
}, {
question: "Sid Clayton",
answer: "[email protected]"
}, {
question: "Sid Clayton",
answer: "[email protected]"
}, {
question: "What colour is a elephant",
answer: "Most elephants are grey but some are red"
}];
//======================================================================================
// create the _infx namespace if it doesn't exist already
_infx = (typeof(_infx) === 'undefined') ? {} : _infx;
_infx.tsearch = function(aArgs) {
var _self = this;
_self.template = null;
$.extend(this, aArgs);
// if no id on the data records then add one
if (_self.data && (_self.data.length > 0) && (typeof(_self.data[0].id) == "undefined")) {
for (var i = 0; i < this.data.length; i++) {
_self.data[i].id = i;
}
}
_self.myFilter = function(item) {
//console.log("search",this.search);
//console.log("fields",this.fields);
item.score = 0;
for (var i = 0; i < this.fields.length; i++) {
var f = _self.fields[i];
item.score += _self.getScore(this.tests, f.weight, item[f.name]);
}
item.mcls = (item.score) ? "" : "nomatch";
};
_self.getScore = function(tests, weight, str) {
var tkn = /[\s\-\,]+/;
str = str.toLowerCase();
var wrds = str.split(tkn);
str = wrds.join(' ');
var cnt = 0;
for (var i = 0; i < tests.length; i++) {
var m;
if (m = str.match(tests[i].reg)) {
...