Introduction
JavaScript is not a difficult language, but you do tend to find yourself typing the same lines of code over and over again. Eventually, when I got fed up with this, I wrote a script to take on some of the work (you can see it here).
It's less than 5k, so importing it into a page [1] won't make a big difference to the load time. It should work with IE5+, NN6+, Firefox, Opera 8+ - in fact, any modern browser [2]. It contains two functions, set() and check(), which are called as follows:
set ('selector property value');
check ('selector property');
Both functions receive information in the form of a string. The parts of the string are separated by a single space, and the string should not begin or end with a space. This is important.
The string passed to set() consists of a selector, a property and a value. The selector can be an id (if you want to change a property of a particular object), or a class name (if you want to change a property of several objects [3]). With check(), the selector must be an id, "screen" or "window", and the string does not require a value.
The selector can also be a global variable (global, NOT local!), representing the class name or id. Using a variable as a selector is covered in the section on Applying behaviour to multiple objects).
The property can be any CSS property. Hyphenated properties lose their hyphens and all words except the first are capitalized – so color stays the same, font-size becomes fontSize and border-left-style is replaced by borderLeftStyle. It can also be "src".
The value can be any appropriate CSS value, or (if the property is "src") the file path of an image. It can also be a global variable. See the section on Setting an object's properties for more on all this.
Notes:
1. For example:
<script type="text/javascript" src="functions.js"></script>
assuming of course that the file "functions.js" is in the same directory as the calling page.
2. The script performs the check:
if (document.getElementById && document.getElementsByTagName)
If the browser is too old to understand either of these methods, it won't run. As always it's imporatant to consider how the page will display in older non-compliant browsers, or ones where JavaScript has been disabled.
3. The script first checks to see if there is an object with the id of the selector. If not, it looks for any objects of that class. Avoid using the same label for both an id and a class (<div id="target_object" class="target_object"... >) as this can cause problems.