|
Now that you have learnt some of the elements that make up JavaScript,
it is time to see them all put into action. The following tutorial
shows how to create a function that swaps the images on a web page
when the user rolls their mouse over them. Before you read this
tutorial, it is advisable that you have read the sections about
functions, variables,
handlers, and parameters.
Lets Begin!
You can view the code at the same time as you read the tutorial by clicking on the button below
Lines 1 & 2 - The function is placed
inside script tags and is positioned in the <head> of the
html document.
Line 3 -The ImageSwp function controls
the rollover images contained in the page. It requires two parameters
- ImgVar(The name of the image) and SourceVar(The name and path
of the image source file).
Line 4 -The script inside the function must be placed within curly brackets{}.
Line 5 -Two variables are created MyObjectStr and MyObject
Line 6 -The 'if' statement checks whether the document contains images. As part of the DOM the names of all images within a document are automatically stored in the 'images' array. If there are no images within the document then the rest of the function will not be processed.
Line 8 -'document.' is joined to
the name of the image (ImgVar) and put into the variable 'MyObjectStr'.
Line 9 -The string contained within
the 'MyObjectStr' variable is converted to an object using 'eval'.
This object is then placed in the 'MyObject' variable.
Line 10 -The image swap now takes
place. The source of 'MyObject' (containing the image name) is now
equal to the image source name and path sent in the 'SourceVar'
parameter
Line 11 -The if statement is closed with a curly bracket.
Line 12 -The function is closed, also with a curly bracket.
The function now lies dormant until called.
|