Tuesday, January 04, 2011

Javascript for My Custom Search




I'm using my new custom search tool to drive the category links in my right sidebar. I have some Javascript that captures the mouse click, does an Ajax call to my search engine, and displays the results. Here's the code:

function process(d) {
 var r=d.result;
 var arLen=r.length;
 var high = r[0].count;
 h="<div class='searchresults'>";
 h+="<h3 class='post-title entry-title'>"+d.title+"</h3>";
 h+="<ol>";
 for ( var i=0, len=arLen; i<len; ++i ){
   if ((high>=1000) && (r[i].count<1000)) {
    h+="<div class='divider'></div>"
    high=0;
   }
   h+="<li><a href='"+r[i].link+"'>"+r[i].title+"</a></li>";
 }
 h+="</ol></div>";
 $("#main-wrapper").html(h);
 Cufon.replace('.searchresults h3');
 window.scrollTo(0,0);
}

$(document).ready(function() {
    $('.categories_div ul li a').click(function() { 
        var href='http://tools.cssrule.com/search?showform=1&
        '+$(this).attr('href').replace(/^(.)*\?/,'')+"&title="+$(this).attr('title');
        href = href.replace(/site%3Acssbakery.com/,'');
        href = href.replace('+','');
        href = href.replace('[','');
        href = href.replace(']','');
        href = href.replace(/"/g,"'");
        href = href+'&callback=?'
        $.getJSON(href, process);
        return false; 
    });
})  

Here's the breakdown on how this works:

$(document).ready(function() {
    $('.categories_div ul li a').click(function() { 
        var href='http://tools.cssrule.com/search?showform=1&
'+$(this).attr('href').replace(/^(.)*\?/,'')+"&title="+$(this).attr('title');

This uses jQuery. The first line registers a callback function with jQuery to be executed when the page is loaded. The function itself then registers a click handler using the selector .categories_div ul li a. That selector targets all my category links.

When a click actually occurs, I construct a URL for the search and store it in the href variable. This is built by pulling out part of the link's href, as well as the link's title attribute and building the URL string from those components. Next we delete any undesirable characters from the URL:

href = href.replace(/site%3Acssbakery.com/,'');
        href = href.replace('+','');
        href = href.replace('[','');
        href = href.replace(']','');
        href = href.replace(/"/g,"'");

I see that I probably could have reduced the code by using a regular expression in the replace, like this: href.replace(/[\[\]\+"]/g,'') instead of doing all the individual replace calls.

Now we make the Ajax call to the server:

href = href+'&callback=?'
        $.getJSON(href, process);
        return false; 

This call goes to a different domain (tools.cssrule.com) so I use a JSONP call (which is done by adding the callback=? string to the URL). When the Ajax call returns, it will call the function 'process'. Finally we return false to keep the user's mouse click from triggering the default action, which would be to follow the link (we don't want the Browser to follow the clicked link since we are already handling the click in our Javascript).

Next we look at the 'process' function that handles the search results. First we just grab some information from the results. The array of results is stored in local variable r. We get the length of that array and store it in arLen. We then pull out the highest score from the results and put it in local variable high:

function process(d) {
 var r=d.result;
 var arLen=r.length;
 var high = r[0].count;

Now we start constructing a HTML fragment and putting it into local variable h. We put in the searchresults div, an h3 for the title, then begin an ordered list:

h="<div class='searchresults'>";
 h+="<h3 class='post-title entry-title'>"+d.title+"</h3>";
 h+="<ol>";

Now we loop over all the results and append list item and link markup to the h variable for each individual result. Also when we see that the scores drop below 1000 we output the divider div:

for ( var i=0, len=arLen; i<len; ++i ){
   if ((high>=1000) && (r[i].count<1000)) {
    h+="<div class='divider'></div>"
    high=0;
   }
   h+="<li><a href='"+r[i].link+"'>"+r[i].title+"</a></li>";
 }

Now we just finish off the ordered list, insert the html fragment into the main wrapper of the page, then call Cufon to make sure the h3 title is rendered correctly, and as a final touch we scroll the Browser window to the very top so the results can be seen.

h+="</ol></div>";
 $("#main-wrapper").html(h);
 Cufon.replace('.searchresults h3');
 window.scrollTo(0,0);
}

And that's it for the Javascript component of the search tool. In another post I'll go into more detail on the PHP that handles the Ajax call on the server side.

1 comments:

IT Consulting said...

Thanks for sharing this helpful post.

Post a Comment

Note: Only a member of this blog may post a comment.