Tag: 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);
			tagSearch.resultBox.innerHTML = data.html;

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

Sitemeter disables IE browsing, hopes no one notices.

Posted by – August 2, 2008

Web Analytics service Sitemeter pushed out an update to their tracking code sometime early this morning. Unfortunately, it contained a bug that would stop Internet Explorer users from being able to access any site using the code. Apparently Sitepoint needs a few more QA testers on their team.

A bugfix has now apparently been pushed out, and the issue no longer exists. Whats interesting, however, is that Sitemeter has made no mention of their snafu. I understand that when the bug is discovered, their primary goal is to get it fixed, not issue official statements. However once they pushed out the fix, a simple “Sorry we screwed up, we just pushed a fix out, let us know if there are any more problems” should be in order.

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


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)
    var scope = this;
    YAHOO.util.Event.addListener(ELEM, EVENT, function(){scope.checkEmail(ELEM);});
    return false;
	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;
           targetElem.innerHTML = "please enter a valid email address";
           targetElem.className = "msgshow";
	   return false;
	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.

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!