Category: Javascript

Google adds ‘Suggest’ feature to homepage

Posted by – August 30, 2008

Google suggest is a handy feature that displays a list of likely search terms as you are typing them. This feature is usefull for several reasons:

  1. It often stops you from having to type your entire search phrase in
  2. It’s a quick way to check the spelling on a word
  3. It gives you an idea of what a good search phrase is that is related to what your after

This feature has been around in google labs for awhile. A form of it is also used in the search bar of firefox (although the search bar only displays phrases, and not the number of results each will return). So the feature itself isn’t new, but making it the default on the homepage for all users (even guests) is a big deal.

I think it is a good move. Of course they want their homepage lite and responsive, but I believe the functionality is worth the extra pageload. Beside, an Ajax search like this really doesn’t take much javascript when done right. In fact, I recently implemented a similar feature for searching tags on able2know.

I implemented it without the help of javascript libraries, although I do have a javascript file I’ve written that contains a small set of usefull tools, such as targeting elements, sending ajax requests, or validating json data. Using these helper functions, my search code becomes this simple:


var tagSearch = {
	init : function(){
		tagSearch.e = $('tagSearch');
		tagSearch.resultBox = $('tagSearchResults');
		tagSearch.original = tagSearch.resultBox.innerHTML;
		tagSearch.e.onkeyup = function(e){
			if(tagSearch.e.value != tagSearch.lastValue){
				tagSearch.lastValue = tagSearch.e.value;
				if(tagSearch.e.value.length > 1)
					Ajax.get('/rpc/tag/search/?s=' + tagSearch.lastValue, null, tagSearch.update);
				else if(tagSearch.e.value.length == 0)
					tagSearch.resultBox.innerHTML = tagSearch.original;				
			}
		}
	}, 
	update : function(r){
		var data = JSON.parse(r.responseText);
		if(data.html){
			tagSearch.resultBox.innerHTML = data.html;
		}
	}	
}

On the php side of things, I am returning html to keep things simple. Pretty easy, eh?

Convert UTC dates to local timezone offset automatically

Posted by – September 11, 2007

So I was working on an application that printed out lots of dates to the user. However, I get traffic from all over the world, and as this is kind-of time sensitive information, I wanted to display the time in their own timezone. I have don’t this before on things like forums, where you allow the user to select their timezone when they register. But what if your users don’t register?

I decided to build a javascript function that would automatically convert from UTC time to the users’ local timezone. This is a pretty simple task, and should work very effectively. I already store the dates in my database as UTC format, which is a good idea to do so that there is never any confusion later as to what timezone a date is in (What if you and/or your server moves?). Also because this is a javascript function, we have the ability to determine the users local time – something that we normally wouldn’t have.

Without further ado, here is the code:


var dateFunction = {
  convertDate : function (gmtDate){
    var originalDate = new Date(gmtDate);
    var retStr = (originalDate.getMonth()+1) + "-" + originalDate.getDate() + "-" + originalDate.getFullYear();
    return retStr;
  },
  init : function(){
    var elems = YAHOO.util.Dom.getElementsByClassName('utcDate');
    for(var i=0;i

As you can see, I am using the YUI library to do some DOM parsing, and unobtrusively add some event listeners. The code should be pretty straight forward, when the page loads I look for all elements with a class of "utcDate" and pass the innerHTML into a separate function. The other function create a new date object, using the original UTC date as the time. By doing this, javascript automatically will display this new date in the users' local time. I can then return the date in whatever format I want. Finally, I replace the innerHTML of the element with the new date string, and we are all set

This provides a simple way to convert dates to local timezone offset, and all the is required is for you to wrap any date you want converted in an element with a class equal to "utcDate". It also degrades gracefully, because without javascript users will simply see the date in UTC format, which isn't really a bad thing, and probably what you would be showing them anyways, if you didn't have this nifty script!

Javascript form validation object

Posted by – July 21, 2007

Today I thought I would share with you what I consider to be a fantastic way to handle form validation in javascript. Of course you need to remember that you have to validate any user input on the server side, but it’s nice to do things on the client side also, so they don’t have to wait as long for a response.

My approach to form validation in javascript involves 2 parts. First off is a extensible object that includes a variety of validation functions that I can have at my disposal. Secondly, I always format my forms with particular IDs, so that I can easily add error messages in javascript. First off, lets discuss the form layout (the easy part). The general rule of thumb here is to create a spot below the form element that will hold the error message, and give it an ID that is the same as the element, with ‘_error’ after it. So


Email:
 

Here the class ‘msg’ simply defines it as being hidden. Then with javascript if we determine email to be invalid, we can set the spans innerHTML to the text we want, and the class to something that will make it appear.

The second part is the fun javascript. What I do is create an empty object which i then prototype out with validation functions. Here is the code:


function Validator()
{
}

/**
 *  Check Email Function
 */
Validator.prototype.checkEmail=function(ELEM, EVENT)
{
  if(EVENT)
  {
    var scope = this;
    YAHOO.util.Event.addListener(ELEM, EVENT, function(){scope.checkEmail(ELEM);});
    return false;
  }
  try
  {
	var elem = this._getElem(ELEM);
	var targetElem = this._findTarget(elem);
	var email = elem.value;
	var regex = /^[-_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\.[a-zA-Z0-9]+$/
	if (regex.test(email))
	{
           targetElem.className = "msg";
	   return true;
	}
	else
	{
           targetElem.innerHTML = "please enter a valid email address";
           targetElem.className = "msgshow";
	   return false;
	}
  }
  catch(e)
  {
	alert("Error in Validator() -> checkEmail(): " + e.message);
	return false;
  }
}

Here I create the object, and a email validation prototyped function. The function takes to arguments: an element, and an optional event. If an event is passed in, it is used to create a listener using the yahoo YUI library. This listener will fire on the given event, calling the same function without the optional argument (and thus running the validation).

The rest of the function is fairly straight forward. It first makes calls to getElem, and findTarget. if getElem is given a string, it returns the element with the given ID. If getElem is given an element, it simply returns the element. findTarget simply gets the ID of the passed in element, and appends ‘_error’, then gets the element with the new string ID.

From there is simply runs a regex expression, and if the regular expression matches it makes sure the error message is hidden, otherwise it sets the text and displays the error message.

This total solution is very portable and easy to use. After including the YUI libraries needed, and the validator code, one can add validation to an element by simply doing:


var validator = new Validator();
validator.checkEmail('email', 'change');

The only custom bit of code is two lines, and you have a regular expression checking the input field every time the field is changed, and will dynamically display an error message when incorrect.

Ajax loading overlay with YUI

Posted by – July 7, 2007

First off, let me say that I love Yahoo’s YUI Library. It seems to be very well thought out, and makes many tasks much simpler.

For Example, let say you upgrade your web app with some tasty Ajax. Now lets assume some of these ajax requests are working a little slow. The proper thing to do would be inform the user that something is happening in the background, so they aren’t lost. YUI makes it easy to display an overlay window with a loading image during the requests.

To do this, we use a Panel object. A panel object is basically a DIV with methods to hide and display itself, as well as advanced display options. Here is some starter code:


ajaxLoadingPanel = new YAHOO.widget.Panel("ajaxLoadPanel", {
width:"240px",
fixedcenter:true,
close:false,
draggable:false,
modal:true,
visible:false,
effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
}
);

What we did here is create a basic panel. The first argument is the elements ID. This can either be an ID of an existing DIV in your DOM, or can be a new ID which will be applied to a dynamically created DIV. The next argument is an Object containing configuration options. These are pretty self explanatory: we set a width, tell it to display in the exact middle of the screen, don’t display a close button, don’t allow the user to drag it, make it a model window, and have it fade in and out. (FYI – a model window just means that it fades everything else on screen).

Next, we fill the DIV with content. If you used an ID of a pre-existing DIV, you can skip this code:


ajaxLoadingPanel.setHeader("Loading, please wait...");
ajaxLoadingPanel.setBody(' ');
ajaxLoadingPanel.render(document.body);

Here we simply set the header and body content of the div, and then add it to the DOM as a child of the body tag.

Good News! We are almost done! The panel is created, now all we need to do is trigger it to open, and close. This is done with the following 2 methods:


ajaxLoadingPanel.show();
ajaxLoadingPanel.hide();

All you need to do is call the show method right before your ajax call, and then the hide method right after recieving your ajax response. Thats it!

Getting Coordinates of a mouse click

Posted by – June 30, 2007

Today I was working on an image editing program, and wanted to determine the x and y coordinates on an image. I knew that imagemaps will give you the coordinates that you clicked on, but I wanted to mimic this behavior in javascript.

It turns out there are 2 ways to do this: If you are using IE (then shame on you!) you can get the coordinates using an offsetX and offsetY.For example, an an onclick handler to your image, passing in the event (ex: <img onclick=’getCoords(e)’ …) then inside the getCoords function, you can use e.offsetX and e.offsetY.

But what If I am awesome, and thus don’t use IE, you might ask. Well, it is only slightly more work. Other browsers give you a pageX and pageY, so you simply have to compare those values with the images values, and do some math to get your coordinates. The image offsets can be found with offsetTop and offsetLeft so to get the x value, you would do:


var xOffset = e.pageX - document.getElementById("thePictureId").offsetLeft

Problem Solved!