background
|
|
Games
Ruffnecks Gaming Gaming for everyone
More

Tombstone
Tombstone Tuning Home of tuning, projects and fast cars and boats.
More

Games
Ruffnecks Gaming
Gaming for everyone
More icon
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
Thau's JavaScript Tutorial
Lesson 4

by Thau!

Page 11 — Functions

Functions are the last bit of basic programming you need to know before you can understand and perform your own serious JavaScripting. All programming languages have functions. Functions, or subroutines, as they're sometimes called, are bits of JavaScript that you can call over and over without having to rewrite them every time.

Let's say you were trying to teach yourself to speed read and you wanted to sprinkle a long text with links which, when hit, would tell you the current time.

For example ... time!

Here's the JavaScript that does this:

<a href="#" onClick="
  var the_date = new Date();
  var the_hour = the_date.getHours();
  var the_minute = the_date.getMinutes();
  var the_second = the_date.getSeconds();
  var the_time = the_hour + ':' + the_minute + ':' + the_second;
  alert('The time is now: ' + the_time);">time!</a>
The details of how this little JavaScript works aren't really important right now; I'll go over them soon. The important thing to notice is that it's fairly long. If you wanted to have 10 of these time links, you'd have to cut and paste this script each time, making your HTML pretty long and ugly. In addition, if you wanted to change the script, you'd have to change it in 10 different places.

Instead of having 10 copies of it on your page, you could write a function to execute the JavaScript. That way you'd have the function in one place, making it easier to edit and easier to read.

Here's how you'd write a timer function.

next page»