background:

javascript ...making shit happen.

Before even looking at this, some other examples will be a good warm-up.

Now on to the example here: the buttons up on the right swap between two different backgrounds. (The flower is by the author of this design; see the site page for details.) This is a fairly simple effect, but it's a good model for a whole range of JavaScript programs. Here are three slightly different versions, of varying levels of sophistication.

code

comments

All of these have the same essential model, which most javascript scripts follow :

  1. An init() function is called when the page finishes loading.
  2. init() sets up other event handlers that connect clicks or whatever on HTML tags to JavaScript functions.
  3. init() may also load images and do any other set-up.
  4. When an event occurs (i.e. a mouseclick), a function (called a 'handler') gets the HTML tag objects, and modifies the properties and/or calls their methods (as defined by the DOM) to alter styles, positions, visibiltiy, or whatever else.

Client side models like this can have a hard time maintaining state between web page loads; see the kite page for a discussion.