Tutorials from October, 2008

Make a Javascript Clock

Although there are many ways to make a clock using Javascript, most use Javascript’s date() object and the setInterval() method. In this tutorial we’ll start by building a clock using these simple functions. Then we’ll explore some interesting ways of optimizing our clock, and hopefully learn a whole bunch of Javascript along the way.

Getting the current time

Let’s kick things off by getting the current time with Javascript. To do so, we will need the Javascript date() object. Remember that this gets the client-side time, e.g. the time in the user’s browser, not the actual time on the server. Client-side time is great for situations like ours, since it takes away any time-zone localization problems.

The date() object is simple enough to use, just instantiate it:

var d = new Date();

Then you can call any properties of this object, getMinutes(), getDay(), getDate(), etc. … (more…)

A Javascript Event Handler Script

Do you remember the dark days of HTML? A million inline properties that were a nightmare to handle even on the smallest websites. Thankfully CSS came along, and good developers now control most of their styling through a centralized stylesheet.

So why shouldn’t we do the same thing with Javascript? A bunch of inline events all over the document with onclick=”” or onmouseover=”” is just as bad as inline styles or font-tags.

However, attaching these event listeners from a central Javascript poses a challenge, since the listener implementation differs from browser to browser. While there are a lot of scripts to attach event listeners, in 2001 Scott Andrew came up with an excellent cross-browser event handler script.

For our Javascript code-library, we’ll use a modification of it:

function addEvent(obj, evType, fn){
if (obj.addEventListener){
(more…)

A Leading Zeros Function

Although Javascript has an excellent method for attaching trailing zeros to decimals, there is no native function to attach leading zeros. For example, if you are dealing in currency, and want ten cents to appear as .10, instead of .1, you would just write:

var theNumber = .1;
theNumber = theNumber.toFixed(2);

Javascript’s toFixed() is great for trailing zeros, but what if you wanted a fixed number of leading zeros? If you wanted 10 to display as 0010?

A leading zeros function is handy tool in any Javascript library, so let’s write one now. We’ll need two variables: a number to format and the number of digits. We’ll change the number into a string, then attach leading zeros (more…)