Auto-complete with JQuery

Posted on Aug 25th, 2009 At 12:41 am by baldo

Recently I coded a JQuery version of a feature I've been using in some projects. Basically this feature is a PHP script that queries a MySQL database and displays a list of possible input keywords using AJAX. It is based on the idea of Google suggest.

Here is an example:

Here is the code to accomplish that fancy behaviour.

Note: I´m using the world database, you can download it from the MySql documentation


autocomp.php

    1 <?php
    2    $USER = "someuser";
    3    $PASS = "somepass";
    4 
    5    $conn =  mysql_connect("localhost", $USER, $PASS);
    6   // R�union  = Réunion
    7    mysql_query("SET NAMES 'utf8'");
    8    mysql_select_db("world",$conn);
    9 
   10    //trim searchKeyword
   11    $searchKeyword = trim($_POST["searchKeywordTmp"]);
   12   //clean searchKeyword
   13    $searchKeyword = mysql_real_escape_string($searchKeyword, $conn);
   14 
   15    if(isset($searchKeyword) && ($searchKeyword)){
   16        $query = "SELECT Name FROM Country";
   17        $query .= " WHERE Name LIKE '$searchKeyword%' LIMIT 5";
   18        if($result = mysql_query($query)){
   19             $flag = 0;
   20             while($dataArray = mysql_fetch_array($result)){
   21                  $data = $dataArray["Name"]; ?>
   22                  <li onclick="fill('<?php echo $data; ?>');">
   23 			<?php echo $data; ?>
   24                  </li><?php
   25                  $flag = 1;
   26               }
   27               if($flag == 0)
   28                  echo "Your search keyword is incorrect."; //empty query
   29         } else
   30              echo mysql_error();
   31     }else echo "ERR";
   32 ?>

suggest.js

    1 var flag = 1;
    2 
    3 function suggest(searchKeyword){
    4    //using ajax and jquery for asynchronous update
    5    $.post("autocomp.php", {searchKeywordTmp: ""+searchKeyword+""},
    6        function(data){
    7           if(data == "ERR")
    8              $("#suggestions").hide();
    9           else{
   10 		    $("#suggestions").show();
   11 		    $("#suggestionsList").html(data);
   12           }
   13        }
   14    );
   15 }//end function suggest
   16 
   17 function fill(thisValue) {
   18    $("#searchBox").val(thisValue);
   19    $("#suggestions").hide();
   20 }//end function fill
   21 
   22 //disable browser' auto-complete
   23 function disAutoComplete(obj){
   24     if(flag){
   25   	obj.setAttribute("autocomplete","off");
   26          flag = 0;
   27     }
   28     window.location = "#tc";
   29     obj.focus();
   30 }

suggest.html

    1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    2     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
    4 <head>
    5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    6 <link rel='stylesheet' type='text/css' href='style.css' media='screen'/>
    7 <script src="js/jquery-1.3.2.js" type="text/javascript"></script>
    8 <script src="js/suggest.js" type="text/javascript" ></script>
    9 </head>
   10 <body>
   11    <p>
   12      <b>
   13        <span id="tc">Type a country name:</span>
   14      </b>
   15    </p>
   16    <input size="30" type="text" id="searchBox" onkeyup="suggest(this.value);"
   17     onclick="disAutoComplete(this);" />
   18    <div class="suggestionsBox" id="suggestions" style="display: none;">
   19 	    <img src="img/upArrow.png" alt="upArrow"
   20         style="position: relative; top: -10px; left: 30px" />
   21 	    <div  class="suggestionsList" id="suggestionsList"></div>
   22    </div>
   23 </body>
   24 </html>

Update:

The example has been changed to save resources in the new server, now I use a screenshot.

Category: PHP, MySQL, AJAX, JQuery


JQuery Scrolling Menu

Posted on Jun 5th, 2009 At 1:39 am by baldo

A lot of people have been wondering how to code a "Scrolling Menu" or animated menu (like in the categories section on my web log). Here are a couple of JQuery code samples to achieve that fancy behaviour.


    1 $(document).ready(
    2 	function(){
    3 		$(window).scroll(function(){
    4 			$('.sidebar').stop();
    5 			var scroll = $(window).scrollTop();
    6 			var menuPosition = 0;
    7 			if (scroll > 370)
    8 			   menuPosition = scroll - 210;
    9 			else
   10 			   menuPosition = 0;
   11 			$('.sidebar').animate({top: menuPosition},'fast');
   12 		});
   13 	}
   14 );

Since the above code snippet consumes a lot of CPU resources, in the following optimization the menu animates on the window's "mouseup" event instead of every time you scroll the window.


    1 $(document).ready(
    2 	function(){
    3 		var scroll = $(window).scrollTop();
    4 		var menuPosition;
    5 		/*
    6 			if the user clicks a link to other page
    7 			and then go back, the menu must be setted to
    8 			its current position.
    9 		*/
   10 		if (scroll > 370){
   11 			menuPosition = scroll - 210;
   12 			$('.sidebar').animate({top: menuPosition},'slow');
   13 		}
   14 
   15 		$(window).scroll(function(){
   16 			$('.sidebar').stop();
   17 			scroll = $(window).scrollTop();
   18 			if (scroll > 370)
   19 			  menuPosition = scroll - 210;
   20 			else
   21 			  menuPosition = 0;
   22 		});
   23 
   24 		$('body').mouseenter(function(){
   25       			$('.sidebar').animate({top: menuPosition},'slow');
   26     		}).click(function(){
   27       			$('.sidebar').animate({top: menuPosition},'slow');
   28     		});
   29 		$(window).mouseup(function(){
   30       			$('.sidebar').animate({top: menuPosition},'slow');
   31     		});
   32 	}
   33 );

Another events must be fired to achieve the same behavior on IE or devices like a mouse with scrolling button, touchpad, etc.. For example, on IE when the user hold the scroll bar and moves up/down, the menu must be animated when the "mouseenter" event of the page's body is fired. On a mouse with scrolling button the same behavior can be reached on the "click" event of the page's body.

Category: JQuery


Improving my web log

Posted on April 9th, 2009 At 6:03 pm by baldo

What's new in my web log?

Recently I finished my new web log design, I have implemented some fancy things with JQuery, adding some CSS and adapted some code in the CMS I'm using. Best of all, my entire web log now has valid XHTML.

And also, I've migrated my web log to another VPS(Virtual Private Server) sponsored by a friend of mine. In later posts I tell you about how funny was the VPS configuration.

What's the future of my web log?

Well, I still don't know about the future, but some people has made great suggestions about its content. They say that I should post more things about me, not just IT stuff, lol !.

That's it for now, feel free to let me know if you have suggestions, comments, bugs reports on this design or whatever you want.

Reach me at:

Category: Personal, JQuery