Friday, June 6, 2008

Javascript Basics: Five functions you should write and use all the time

If you're new to Javascript, you've either already found out or will very shortly that there are some tasks that you need to do all the time. It can get pretty tedious having to remember what the code is for those tasks, or even worse, knowing what the code is, but still having to type it out each time you want to use it.

In this article, I'm going to walk through the first of five functions I use frequently when writing Javascript code that will make not only make writing code easier because the code is more concise, but also because in a lot of cases it's easier to understand. Certainly this series won’t cover all of the shortcut functions you may want to write, but if you're new to Javascript this should get you going so that soon you can write your own. So let's get started:


1. $() or id()


If you've written Javascript for more than 15 minutes, you've probably used the “document.getElementById” function. If you've written Javascript for more than 30 minutes, you've probably made the mistake of capitalizing the last "d" and had a Javascript error thrown. Hopefuly the error message from the browser made it obvious what was wrong, but in some browsers deciphering the error message can be an art in itself. Because it is easy to misspell and requires typing out 24 characters to accomplish one of the most basic and frequent tasks in Javascript, it doesn’t take long to get frustrated with the “document.getElementById” function.

If you've ever used the popular jQuery library, you know you can get a reference to an HTML element by writing:


var referenceToElement = $("elementID");


The folks who wrote jQuery felt your pain in writing out "document.getElementById" each time, and made a shortcut function whose name was just the dollar sign. Because the dollar sign is a valid character for use in a Javascript function name but it's not a character that is often used, they chose to create a function that was only one character long to effectively act as an alias for the "document.getElementById" function.

This was such a great idea, we’ve copied it for ourselves at APT and included it in our own Javascript library by writing the following function: (Note: If you use jQuery already, there’s no need to write this function yourself since you already have it!)


$ = function(id) {
// If "id" is a string, return the value of "document.getElementById",
// otherwise, just return whatever was passed in.
return (typeof id == "string") ? document.getElementById(id) : id;
}


Armed with this code, we can now replace all instances of "document.getElementById" with the much shorter "$".

Another side benefit of using this function that hasn’t been mentioned yet is that every time we get a reference to an element, we've reduced the size of our code by over 93% (well, not exactly, but you get the idea). If you add the space saved across a large Javascript file by making this replacement, the result is usually pretty significant.

You'll also notice from our implementation, that when we call our “$’ function, we’re not just directly calling the “document.getElementById” function. Instead we built a little bit of extra functionality into our “$” function.

Notice that if you pass in an object that is not a string, our function won't throw an error, it will just pass back the same object that was passed in. This can be useful in functions where you want your code to be flexible for whoever is using it so that they can pass in either a string that is the ID of an HTML element or a reference to the HTML element itself. At the top of your code you can pass that object through our “$” function, and rest assured that what is returned is a reference to a HTML element.


function myCoolFunction(eitherAnIdOrAnElementReference) {
var definitelyAnElementReference = $(eitherAnIdOrAnElementReference);
// Do something to that element...
}


As a final point, some people don't like using the dollar sign as the function name. You can feel free to name this function whatever you want. For instance, you could name it "id" instead. I prefer using "$" because I can imagine writing code where I name a variable "id" and accidentally overwrite the function I created, which could then lead to all sorts of funky errors. If I use "$", the chances of that happening are greatly reduced.

Alright, so one down. I'll post the next two functions tomorrow which are related to showing and hiding HTML elements.