Inline Search

I’ve implemented a new feature on my blog, which I think is pretty cool. Over the the right is a new box labelled: Beta: Inline Search. Try typing something into it, and pressing return, or clicking the button. Wait a few seconds (depending on connection speed) and search results for this blog should appear underneath. It’s still fairly rudimentary – I plan to make a “working” indicator, plus the ability to search for more results. But I guess you want to see the code…

 1     function SearchBlog(){
 2         window.searchreq = new XMLHttpRequest();
 3         var s=document.getElementById("s").value.replace(/ /g,"+");
 4         searchreq.open("POST","/category/&s="+s);
 5         searchreq.onload = UpdateSearchResults
 6         searchreq.send("")
 7     }
 8     
 9     function UpdateSearchResults(){
10         if (searchreq){
11             if (searchreq.status==200) {
12                 data = searchreq.responseText.split("<body>")[1].split("</body>")[0];
13                 temp = document.createElement("div");
14                 temp.innerHTML = data;
15                 if (temp.getByClass) {
16                     results = temp.getByClass("post-title");
17                 }
18                 var resList = "Results:<ul>";
19                 for (var i=0;i < results.length; i++){
20                     resList = resList + "<li>"+results[i].innerHTML+"</li>";
21                 }
22                 resList = resList + "</ul>";
23                 document.getElementById("searchresults").innerHTML = resList;
24                 data = "";
25                 temp = "";
26                 resList = "";
27             }
28         }
29     }

You will need to have a getByClass() function installed – if you don’t, it’s:

 1     /* 
 2         Thanks to Dustin Diaz for this one:
 3         http://www.dustindiaz.com/getelementsbyclass/
 4         */
 5     document.getByClass = function(searchClass,tag){
 6             var classElements = new Array();
 7             if (tag==undefined){tag="*";}
 8             var els = this.getElementsByTagName(tag); // use "*" for all elements
 9             var elsLen = els.length;
10             var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
11             for (i = 0,j = 0; i < elsLen; i++) {
12                 if ( pattern.test(els[i].className) ) {
13                     classElements[j] = els[i];
14                     j++;
15                 }
16             }
17             return classElements;
18         }

BarbarellaFerrante & TeicherUltra-Lounge, Vol. 16: Mondo Hollywood ★½