JavaScript can be used to modify the content of a webpage in certain ways.
One of the most common dynamic visual effects done with JavaScript is
changing an image when the user moves the mouse cursor over it.
First things first
JavaScript scripts are usually placed directly in the HTML document. The
HTML tag used is the <SCRIPT> tag. This presents a
problem when an older web browser is used that doesn't support JavaScript.
To prevent the script from being displayed in these older browsers, the
script is placed in HTML comments. All JavaScript is usually enclosed
in the following:
<SCRIPT LANGUAGE="JavaScript">
<!--
// -->
</SCRIPT>
var keyword
The var keyword is used to declare variables in JavaScript.
Variables in JavaScript do not have a type associated with them as in other
languages. The type of variable is assumed from context and all numbers
are considered to be floating point numbers.
Image objects
To create a mouse rollover effect, you need to store two images in
JavaScript variables. JavaScript can be used to change the content of
images on a page, but the size of the image must remain the same.
Changing Images with Mouse Movement
The following goes in the header of the HTML document:
<SCRIPT LANGUAGE="JavaScript">
<!--
var redarrow=new Image(10,5);
redarrow.src="red.gif";
var bluearrow=new Image(10,5);
bluearrow.src="blue.gif";
// -->
</SCRIPT>
The following is the actual link in the body section:
<A HREF="next.html"
onMouseOver="document.Arrow.src=redarrow.src; return true"
onMouseOut="document.Arrow.src=bluearrow.src; return true">
<IMG SRC="blue.gif" NAME="Arrow" WIDTH="10" HEIGHT="5"
BORDER="0" ALT="next">
</A>
This will create an image that is 10 pixels wide and 5 pixels high. If
either of the image files red.gif or blue.gif
were a different size, then they would be resized to fit the 10 by 5 pixel
area. onMouseOver is an attribute of the A HREF
tag that specifies JavaScript commands to execute when the mouse moves over
the link. Similarly, onMouseOut specifies what is executed
when the mouse leave the area of the link. document.Arrow
refers to an element of the current document called Arrow, which
is specified under the NAME attribute of the IMG
tag. Because the actual image is contained in the src
property of the image object, we can change the image by assigning the
source of the red arrow (redarrow.src) to the source of the
arrow in the document (document.Arrow.src). The last JavaScript
statement must be return true, or something that evaluates
to true. Otherwise, the image will not be changed.
|