Introducing JavaScript

Introduction

JavaScript is a small programming language that works well in HTML pages. It allows you as a web programmer to do things on a web page that you might otherwise not be able to accomplish, like the way the quiz at the top of this page functions. JavaScript is used to make a page “come alive” and be more interactive with the person viewing the web page.

JavaScript Rollovers


One common application of JavaScript is the rollover, which allows an image to “change” when the mouse pointer passes over it. Often menu items may appear to glow or change colors when the mouse is positioned on top of the menu. In the following example, the “Back” image appears to glow when you move the mouse over it.

Click to go back

This image is really a set of two separate images. The one you see normally is named back1.jpg, and when the mouse pointer moves over the image, it is changed to back2.jpg. The following code demonstrates how this happens:





Example 1

<img src=”images/back1.jpg” alt=”Click to go back” name=”back”
onMouseOver=”document.back.src=’images/back2.jpg’
onMouseOut=”document.back.src=’images/back1.jpg’“>

Let’s look at Example 1. The img tells the browser that we have a normal image, and the source file and alternate text are specified in blue. For an image to be changeable, it needs to have a name, which is specified in red. Although the name could be anything, the example uses the name back. Finally, there are two JavaScript events which cause simple lines of JavaScript code to run. The first, onMouseOver, occurs when the mouse pointer is moved over the image. When this happens, the code (in green) is executed. This code changes one of the properties of the image, specifically the src property of the image named back, part of the web document. The new image source is set to a different file: back2.jpg. A separate event, onMouseOut, executes code when the mouse pointer is moved off of the image, returning the image source to the original file.

NOTE: You can not have two different images named the same thing.

Rollover Links


Usually, these rollovers are used for image links. In this case, the image tag shown in Example 1 is placed within a link tag. In this case, the image border is usually set to 0 so that a link box is not drawn around the image.





Example 2

<a href=”main.html”>
<img src=”images/back1.jpg” alt=”Click to go back” border=”0″ name=”back”
onMouseOver=”document.back.src=’images/back2.jpg'”
onMouseOut=”document.back.src=’images/back1.jpg'”>
</a>


Practice:

  1. In your practice folder, create a file called rollover.html.

  2. Add an image link to the web site www.dog-play.com using these images in a rollover: dog1.gif and dog2.gif.