javascript ...making shit happen.
Before even looking at this, some other examples will be a good warm-up.
- From JavaScript - Definitive Guide v5 (see David Flanagan's website)
- Jim's style changing example
- www.quicksmode.org - JavaScript examples
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
- First version : javascript handlers defined within the .html. This is what a typical 'free script' might look like, and what most beginner javascript folks would do. Simple and it works.
- Second version : no javascript in .html; explicit .js code with hard-coded button names. This heading towards a more 'modern' approach that keeps the presentation HTML separate from the JavaScript program. Becoming more common.
- Third version : again no javascript in .html; general-purpose .js code that'll handle any number of background buttons. This is the sort of thing I'd expect an experienced programmer to write; the JavaScript and HTML are fairly independent of each other. More buttons and their backgrounds could be added to the .html file, and the JavaScript would just do the right thing.
comments
All of these have the same essential model, which most javascript scripts follow :
- An init() function is called when the page finishes loading.>
- init() sets up other event handlers that connect clicks or whatever on HTML tags to JavaScript functions.
- init() may also load images and do any other set-up.
- 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.