HTML and CSS Reference
In-Depth Information
Listing 6-29.
Variables
var now = new Date();
var year = fourdigits(now.getYear());
This code provides the current year, which can be used for a “dynamic” copyright content as Listing 6-30.
Listing 6-30.
Inline JavaScript Example
Copyright ©
<script type="text/javascript">document.write(year);</script>
John Smith
This is an inline JavaScript code. In this case, it will represent the current year between the copyright sign and the
name, as shown in Listing 6-31.
Listing 6-31.
The Result of Listings 6-28, 6-29, and 6-30
Copyright © 2011 John Smith
Note that if the JavaScript code cannot run for whatever reasons, the other parts of the document are still
rendered (Listing 6-32).
Listing 6-32.
The Result of the Same Code with JavaScript Disabled or Without JavaScript Support
Copyright © John Smith
Event Handlers
JavaScript is often used to provide control over document elements or the browser window according to user
interaction such as clicking an element with the mouse.
Assume three images on a web page intended to modify the font size of the
main
layer when the user clicks them.
Listing 6-33 shows a possible solution.
Listing 6-33.
Functions to Manipulate the Font Size
function normal() {
var esize = document.getElementById('main').style;
esize.fontSize = "1.1em";
}
function larger() {
var esize = document.getElementById('main').style;
esize.fontSize = "1.4em";
}
function huge() {
var esize = document.getElementById('main').style;
esize.fontSize = "1.8em";
}
These three functions can be written either within the
script
tags in the document or in the external file
font.js
. In the latter case, they can be loaded with the
src
attribute of the
script
element as discussed earlier in
Listing 6-27 (the file path and name can be arbitrarily modified).
Now the appropriate event handler function can be loaded with the
onclick
attribute (Listing 6-34).
Search WWH ::
Custom Search