Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

Build a Web 2.0 Document Search Site

by

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.


Advertisement