Build a Web 2.0 Document Search Site

In this article, we will create a document searching site with jQuery. This site will be used to search documents by specifying an extension (file type). The data is then filtered and sent to Google. We’ll learn many jQuery tips and skills through the process. A gray box plugin called “ColorBox”, and a toolTip plugin called “SimpleTip” will also be introduced in this article. Let’s get started.


Introduction

Nowadays, the most useful tools for surfing the web are search engines like Google, Yahoo and MSN live. Unfortunately, not everyone knows how to use these tools efficiently and properly.

In this article, we will use one small Google search trick to create a Web 2.0 style website. From this site, the user can search the documents by entering a keyword and selecting a specific file type. I will pay more attention to the jQuery usage in this site build process. Once completed, our completed project should look like the following.

Step 0: Resources: Logos and Icons

Of course, if you want, you can create your own logos or icons with Photoshop. But, if you are a lazy man, like me, you can download them online. However, please pay attention to the license, because some of these resources are not allowed for commercial use.

creatr is a great site which provides a service to create Web 2.0 style logo online. Most importantly, it’s free and easy to use! There are many styles you can choose to create your logo. I chose something like the following.

The icons used in this article are all from the Windows operation system. If you’d rather use other icons, review iconza and weloveicons to find beautiful icons. Also, you can use an icon search engine to find icons on the internet. Go to iconfinder or iconlook to have a try.

Step 1: Page Layout

Our front page will be similar to Google.com. A brief initial sketch looks like the following:

The HTML code for this page is as follows.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<title>Search Documents with Google!</title>
	</head>
	<body>
    <div id="header">
        <a href="#"><img src="images/logo_docs.gif" /></a>
    </div>
	<div id="wrapper">
		<div id="types">
		<a href="" value="doc" id="doc" title="documents in Microsoft Word (DOC)"><span>DOC</span></a>
		<a href="" value="pdf" title="documents in Adobe Acrobat (PDF)"><span>PDF</span></a>
		<a href="" value="xls" title="documents in Microsoft Excel (XLS)"><span>XLS</span></a>
		<a href="" value="ppt" title="documents in Microsoft Powerpoint (PPT)"><span>PPT</span></a>
		<a href="" value="rtf" title="documents in rich text format (RTF)"><span>RTF</span></a>
		<a href="" value="txt" title="documents in Text-format (TXT)"><span>TXT</span></a>		
		<a href="" value="bat" title="documents in MS-DOS (BAT)"><span>BAT</span></a>
		</div>
		<div>
			<input type="text" name="word" id="word" size=65 maxlength=100/><br/><br/>
			<a id="google" href="http://www.google.com">Search Docs</a>
		</div>
	</div>
    <div id="footer" >
    <div id="footLinks">
    <a title="about" href="" target="_blank">About</a>  |  
    <a title="contact" href="" target="_blank">Contact</a>  |  
    <a title="thanks" href="" target="_blank">Thanks</a>  |  
    </div>	      
    Search results come from <a href="http://www.google.com">Google</a>, this site has no assosiation with Google Inc.
    <br/>    
	Copyright © 2009 This is just a demo site.(BETA).<br/><br/>
    </div>
    </div>
	</body>
</html>

Next, we should add some styles to the page, to make it more readable and beautiful. We create a new file called style.css to save the styles used in this example.

body{
    font:12px/1.5 Tahoma, Helvetica, Arial, sans-serif;text-align:center;
    margin: 0px;
    background-color:#f9f9f9;
}
a:link, a:visited{
    text-decoration:none; color:#6599CB;
}            
#header {
    text-align: center;
    padding: 70px 0px 40px 0px;
}
#header a img{
    border-style: none;
    margin: 0px;
}
#types{padding:15px;}
#types span{margin-left:25px; }
#word {
text-align: center;
font: 15pt/17pt bold "Helvetica" normal;
padding: 5px 10px 5px 10px;
width: 40%;
border: 3px solid green ;
}
#google{
    color:#fff;
    background:green;
    font-size:15px;
    text-decoration: none;
    font-weight:bold;
    margin: 10px 5px 10px 5px;
    padding:5px 10px 5px 10px;
    line-height: 15px;
}            

#wrapper{
    text-align:center;
}
#footer {
    text-align: center;
    margin: 50px 0px 0px 0px;
    border-top:1px solid #E4E4E4;
    color:#808080;
    float:left;                
    width:600px;
    position: relative;
    left:50%;
    margin-left: -300px;
}
#footer div	{margin-top:5px;}
#footer #about, #footer #contact, #footer #thanks {
  display: none;
  text-align:left;
  margin: 10px;
  padding: 10px;
  background-color: #FFFF99;
}		

Let’s not forget to reference our external CSS file.

<link type="text/css" media="screen" rel="stylesheet" href="css/style.css" />

Now your page should look like the following:

Pay attention to this piece of styling, which forces the content on the page to stay centered.

#footer {
    float:left;                
    width:600px;
    position: relative;
    left:50%;
    margin-left: -300px;
}

Step 2: Implement the Search Function with jQuery and Google

The main function of this site is to search documents with specified file types, such as “PDF”, and “DOC”. If you’re well-versed in search engines, you might already know how to accomplish this. If we want to search for PDF documents about “jQuery”, we can enter the following text in the search text box:

jQuery filetype:PDF

jQuery is a great Javascript framework which provides an easy-to-use JavaScript freamework. If you are reading this article, I think you should have basic jQuery skills by now. But if not, that’s also fine. We will start our work from the beginning.

We create a new file to save the Javascript/jQuery codes used in this example. The name of this file is main.js, which will be put in directory js. The reference code used in HTML file is…

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1.3.2");</script>
<script type="text/javascript" src="js/main.js"></script>

The first two lines are used to import the jQuery library file from Google’s CDN. If you’d rather, you can instead use your local jQuery library file.

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

Within main.js, add the following script, which will be run after the DOM is ready.

$(document).ready(function(){
//place your codes here
});

We want to add the file type icons before the file type texts above the search box.

$(document).ready(function(){
    $("#types a").each(
        function(){                 
            $(this).css({ "background":"transparent url('icons/" + $(this).attr("value") + ".gif') no-repeat 4px center", "height": "100%"});            
        }
    );
});

The icons are placed in our “icons” directory, and the name of icons are set as (filetype).gif. So in the above code, we can use the selector $(this).attr(“value”) to get the file type name, such as “pdf”, “doc”, etc. Then we can grab the icon file name, which can be used to set the background image of the element. In the above code, function css() is used to set the CSS style of the element $(“#types a”).

Now the file type above the search box should look like:

But, as you can see, when the page is reloaded, we can’t distinguish which file type we have selected.

We’ll change the styles every time a user click on an icon. The onClick event will be triggered after the user click on one link.

    $("#types a").click( 
	  function () {            
        $("#types a").each(
            function(){
                $(this).css({ "background-color":"",  "padding" : "", "color":"#6599CB", fontWeight:"normal"});
            }
        );
        $(this).css({ "background-color":"#6599CB", "padding" : "5px", "color":"white", fontWeight:"bolder"});
        return false;
    });   

Here, we use different background color to make the selected file type appear differently. Now, the selected file type link looks like:

But, the problem is, after the page is reloaded, any file type will be selected. We need to give a default selected file type after the page has been refreshed.

$(document).ready(function(){
    /* initialize the data "filetype" */
    $("#types a:first").click();
});

Every time the page is reloaded, the first link in within file types section will perform a “click” operation.

Search Function

Next, we will implement the search function. When a user click on the “Seach Docs” button, he will be redirected to the result page, which is provided by Google. A function called updateLink() is used to update the link on this search button when user inputs his keywords.

    
function updateLink() {
        $("#google").attr("href", "http://www.google.com/search?q=" + encodeURI($("#word").val()) + "+filetype%3A" + encodeURI($("#types").data("filetype")));
    }	

In the above code, we use attr() function to update the href attribute of the search button (link). $(“#word”).val() is used to grab the key words in the search box. $(“#types”).data(“filetype”) is used to get the file type, which will be set in $(“#types a”).click() function. And also in this function, updateLink function will be called, which means, the href attribute of the search button will be updated each time that the file type is changed.

        
$("#types a").click( function () {            
        $("#types a").each(
            function(){
                $(this).css({ "background-color":"",  "padding" : "", "color":"#6599CB", fontWeight:"normal"});
            }
        );
        $(this).css({ "background-color":"#6599CB", "padding" : "5px", "color":"white", fontWeight:"bolder"});
        
        $("#types").data("filetype", $(this).attr("value"));					
        updateLink();      
        $("#word").focus();
        return false;
    }); 

We’re almost finished. But wait, now, if a user changes the search keyword after selecting file type, what will happen? The href attribute of the search box will not be updated. That’s not what we want. So we also need to compensate for this possibility.

        
    /* update the link when "#word" changes */
    $("#word").keydown(function(e){
        updateLink();
    }).keyup(function(e){
        /* submit search with "enter" key */
        if(e.keyCode == '13') {
            $("#google").click();
        }
    });  

In the above code, everytime the $(“#word”) is changed, e.g, the user changed the key words in search box, the function updateLink will be called to update the link of the search button. Let’s also add one more convenience. When a user presses “Enter”, we’ll assume that the user means to mimic the functionality of the “Search” button. We know that the keycode is 13, which means the “Enter” key has is pressed — we will trigger the onClick event of the search button.

Now, when we type something into the search box, the result will be displayed as the following picture. It will redirect to Google’s search result page.

Step 3: Display the Search Results with the jQuery ColorBox Plugin

ColorBox is a great jQuery plugin which can be used to make a light-box effect. For detailed usage of this plugin, you can refer to its website.

First of all, we should download the ColorBox plugin from the offical website. The latest version is 1.2.4, at the time of this writing. Before we can use it, we need to link to the Javascript file.

        
<head>
		<link type="text/css" media="screen" rel="stylesheet" href="colorbox/colorbox.css" />
		<link type="text/css" media="screen" rel="stylesheet" href="colorbox/colorbox-custom.css" />
		<!--[if IE]>
			<link type="text/css" media="screen" rel="stylesheet" href="colorbox/colorbox-custom-ie.css" />
		<![endif]-->
		<script type="text/javascript" src="colorbox/jquery.colorbox.js"></script>
</head>
  • colorbox.css and colorbox-custom.css are used to control the appearance of the light-box.
  • colorbox-custom-ie.css contains some hacks only for Internet Explorer.
  • jquery.colorbox.js is the ColorBox plugin file.

The ColorBox plugin can be instantiated like so:

    /* setup colorbox plugin */
    $.fn.colorbox.settings.transition = "fade";
    $.fn.colorbox.settings.bgOpacity = "0.8";
    $.fn.colorbox.settings.contentCurrent = "({current}/{total})";

The id of the search button is “google”, so we can use the selector “$(“#google”)” to get this element. The ColorBox plugin can be used as follows:

    $("#google").colorbox({contentWidth:"800px", contentHeight:"500px", contentIframe:true});

We’ve set the content width to 800px and the height to 500px.

Step 4: Add Tooltips with the SimpleTip Plugin

SimpleTip is a simple jQuery tooltips plugin. It’s lightweight and easy to use. We can download it from its official site.

Once again, let’s reference the script.

    <script type="text/javascript" src="js/jquery.simpletip-1.3.1.min.js"></script>

We should also define the tooltip’s appearence with CSS.

.tooltip{
   position: absolute;
   padding: 10px 13px;
   margin: 0px 0px 0px 10px
   z-index: 2;
   
   color: #303030;
   background-color: #f5f5b5;
   border: 2px solid #DECA7E;
   font-size: 12px;
   line-height: 15px;
   text-align: center;
}

We can add this style definition into our style.css file.

Now we want to add the tooltip to these file type links. The tooltip will appear when the user hovers over each file type link. The tooltips will display more detailed file type information.

    $("#types a").each(
        function(){                 
            $(this).css({ "background":"transparent url('icons/" + $(this).attr("value") + ".gif') no-repeat 4px center", "height": "100%"});
            $(this).simpletip({ showEffect: 'slide', hideEffect: 'slide', position: 'top', offset: [0,-10],content: $(this).attr("title")});
        }
    );

Simpletips has many parameters to create the effect. In the above code, the show and hide effect are set as “slide”, and also the tooltips contents are set as the same with the “title” attribute of each file type link.

Step 5: Add Bookmarkets to the Footer with the addThis Widget.

To share with your friend via some social networking sites, such as del.icio.us, digg, myspace, facebook, twitter and so on, Addthis provides a great, and free, service.

We can use the code from the official site, and normally, it looks like like the following:

    <!-- AddThis Bookmark Button BEGIN -->
    <script type="text/javascript">
      addthis_url    = location.href;
      addthis_title  = document.title;
      addthis_pub    = 'jiji262';
    </script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12" ></script>
    <!-- AddThis Bookmark Button END -->  

You also can set some styles for what these buttons display. Here we put the code into the footer of our example page. The result should look like:

Step 6: Animate the Footer Content.

The last step of this example is to create the animation when a user click on the footer links, like “About”, “Contact” and “Thanks”.

    <div id="about">
        <h3>About</h3>
        <b>Search documents on google, it can not be easier.</b><br/><br/>
        This site is designed for Google beginners to search documents of mutiple formats quickly.<br/><br/>
        Enjoy it!!! <br/><br/>
    </div>
    <div id="contact">
        <h3>Contact</h3>
        Feel free to contact me at any time and about anything, this site or other topics.<br/><br/>
    </div>
    <div id="thanks">
    <h3>Thanks</h3>
    There are many people I want to thank, who had made a very great job on web development, which made me realize this page easier. <br/><br/>
    1. <a href="http://jquery.com/">jQuery</a>: A Easy to use but great and strong javascript framework.<br/> <br/>
    2. <a href="http://colorpowered.com/colorbox/">ColorBox</a>: A light-weight, customizable lightbox plugin for jQuery.<br/><br/>
    3. <a href="http://craigsworks.com/projects/simpletip">Simpletip</a>: A simple tooltips plugin fro jQuery.<br/><br/>
    </div>

This code will be placed in the div tag which has an id of “footer”. Then we can add a bit of jQuery to control the display.

    /* handle footer links display */
    $("#footLinks a").toggle(function(){
        $("#footLinks a").each(function(){
            $("#" + $(this).attr("title")).hide('fast');
        });

        $("#" + $(this).attr("title")).slideDown('slow');
        return false;
    },  function(){
        $("#" + $(this).attr("title")).slideUp('slow');
        return false;
    }
    );

slideDown and slideUp function are used to create the animation effect. The footer of this page will be displayed as the following picture.

We Are Done!

We’ve now created a complete Web 2.0 site document search portal. What are your thoughts? Thanks so much for reading.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.quizzpot.com Crysfel

    Awesome!! thanks for share :D

  • B£3

    Nicee :)

  • Rik Girbes

    I like it!

    I personally think this tutorial is great for getting some interesting stuff out of..
    but it isnt the best one for e.g. using it right away……..

    Thanks Though, i did got some nice things out of it!

    Rik

  • http://www.shopandlist.me Karim

    very nice thanks :-)

  • Rik Girbes

    bye the way i would blend out your email just a little bit more on one of the pictures (your gmail account), it is readable,… (when looking at your screen from a different angle)

    ps. Sorry for the double post…..

    Rik

    • http://www.peewee1002.co.uk Peewee1002

      In the post under it, it is clearly re-able with any bluring.

      http://nettuts.s3.amazonaws.com/352_documentSearch/8.jpg

      • Linghucong

        eh~~~ I forgot to process it:>
        But it’s not a secret.

    • http://laranzjoe.blogspot.com lawrence77

      hahah i also come to tell about that, but already u guys made that…. :lol:

  • http://mustardamus.com/ Mustardamus

    I would not use toggle() on the multiple links in the footer. It stop working properly after the third “toggle”.
    Just my 2c code:

    $(‘#footlinks a’).click(function() {
    $(‘#footer div:not(#footLinks,#copyright)’).slideUp(‘slow’, function() {
    $(‘#’+$(this).attr(‘title’)).slideUp(‘slow’);
    });
    return false;
    });

    We could get rid of the “:not()” selector if the markup would be different.
    (Code is not tested, but something like that ;))

    • http://mustardamus.com/ Mustardamus

      $(’#’+$(this).attr(’title’)).slideDown(’slow’); //of course

  • http://labs.dariux.com Dario Gutierrez

    Definitely good useful tool. I like it. =)

  • http://coreyworrell.com Corey Worrell

    Half the time the text you enter to search for, the last letter is stripped off. I tried searching for ‘test’, but it only actually searched for ‘tes’. This happened almost every time.

    Also, if you try hovering over a tooltip, it freaks out and keeps “blinking” until you remove your cursor, and then it still continues for awhile.

    • Linghucong

      Yes, thanks for your concern. I didn’t find this bug when posting it.
      You can fix it as the following way.

      /*fix: input and push button, the last character missing */
      $(“#google”).mousedown(
      updateLink
      );
      Welcome to contact me (email or comments) if you have any better idea.

  • Simon

    Didn’t have the time to read the whole article but I guess I encountered a bug. The last letter of your search disappears in the google search (at least if you”re searching for some bat files).

    I’m going to read the rest of this interesting article later, thanks anyway !

    • http://blog.donews.com/jiji262 Linghucong

      Yes, I am afraid you are right. please see my comments to Corey Worrell.

  • http://laminbarrow.com Lamin Barrow

    Cool tut. trendy :)

  • http://myfacefriends.com Myfacefriends

    this is very good indeed! thank you for bringing up this wonderful tuts!

  • http://www.ediyang.com eddie

    nice post!i gonna to make another site like this,thank you for advicing.
    and colorbox is a awesome plugin

  • http://www.webcoursesbangkok.com Carl – Web Courses Bangkok

    Fantastic tutorial and very useful for people who constantly search and need a quick self made tool.

  • Rohan

    Problem: When you search, the last letter is omitted. Example:searching for “net” results in a google search for “ne”

  • Jack F

    I would prefer to use e.preventDefault() rather than return false in my links.

    Good tutorial, enjoyed it.

  • http://www.dreamcoders.com.ar/ Christian

    It’s cool tutorial.
    Thanks

  • http://wisdomboost.org JP

    This my friend, is one HELL of an article!

    Thank you SO much!

  • http://www.dsaportfolio.com.br Diego SA

    Wow! That’s awesome! I’ll keep my eyes on it!

  • http://www.massbase.com Massbase

    The logo is the only thing that makes it 2.0 ? lol

  • http://www.allisclear.com Stefan Ashwell

    Nice tutorial thanks very much :)

  • http://www.livecube.es seeal

    wooh :O thx¡

  • http://www.twitter.com/benoa Ben

    People should read comments before they post one. That’d make a better web.

  • elkaz

    1. #footer {
    2. float:left;
    3. width:600px;
    4. position: relative;
    5. left:50%;
    6. margin-left: -300px;
    7. }

    That is a terrible example of CSS, when it should simple be:

    1. #footer {
    2. width:600px;
    3. position: relative;
    4. margin: 0 auto;
    5. }

    • http://slackrmedia.com SuperMario290

      Being kind of harsh, but good way of simplifying things.

  • douglasfugazi

    thanks for tip :)

  • jeff

    anyway to add adsense to this

    • anonyme

      think you

  • http://www.itsyllabus.com itsyllabus

    great tutorial to make it possible

  • http://ideasep.com ide

    it’s amazing .. nice tutorial. thanks

  • http://www.chubweb.com chubweb

    its cool one, many thanks :D

  • http://technotweets.com Devang

    Thats a good one.
    I like the way the footer is animated and the tooltip stuff.

  • Nico

    great tutorial! but i have one question… is it possible to search on diffrent sites eg: i click doc i will search on google and when i click pdf it will search on bing… ist it possible?

  • http://www.dev-hq.co.uk Joe

    Great Tut!

  • Zoran

    Thanks for the tut, it’s cool!

  • http://night-fairy-tales.com/ SM

    Great solution! Thanks

  • http://www.xcellence-it.com/ Xcellence IT

    thanks for sharing this great tutorial… I learned a lot of things using this…

  • http://www.missold.info Rowe Niez

    great tutorial! is it possible to include yahoo search, bing and google in one search?

  • Aaron

    Awesome!!!!!!
    But can anyone tell me that how can i create a search engine for my own site
    As M’ creating site for education and M going to add some solutions of some question on the site so I want that users can search for it AND for that I need a search to search in my own site only!!!!!!

    CAN Any one help me?

  • http://www.2cybersearch.com devan

    hello, thanks for this tutor. but i have tried demo site. the demo not working until now