lesson 5: introduction to eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding...

19
JavaScript 101 | 5- 1 Copyright © August 2002 Pace University Lesson 5: Introduction to Events OBJECTIVES: In this lesson you will learn about Event driven programming Events and event handlers The onClick event handler for hyperlinks The onClick event handler for buttons (forms) The mouse event handlers onMouseOver and onMouseOut

Upload: others

Post on 07-Jun-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 1

Copyright © August 2002 Pace University

Lesson 5: Introduction to Events

OBJECTIVES: In this lesson you will learn about

Event driven programming

Events and event handlers

The onClick event handler for hyperlinks

The onClick event handler for buttons (forms)

The mouse event handlers onMouseOver and onMouseOut

Page 2: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-2| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

Preparing to Program

A popular feature of the World Wide Web is its interactive nature. When you access a Web

page, you don't just view the page, you interact with it. You click on links and buttons to

change pages, make windows pop up, or enter information in forms and view responses

based on your entries. In these and many other ways, Web pages are responsive to your

actions. In other words, Web pages are event driven, reacting to events that you initiate such

as mouse clicks or keyboard entries.

An event is an action by the user. Some examples of events are:

clicking a button;

moving the mouse pointer over a hyperlink;

changing the contents of a text box;

entering or leaving a text box.

Event driven programs use events as triggers for program execution. Events signal requests

and commands from the user that the program carries out by executing code.

In this lesson, you will learn to use JavaScript to control event driven Web pages. You will

use buttons and hyperlinks to initiate actions, and you will learn how you can use JavaScript

to make a Web page respond to mouse events to display different images.

Event driven Programming

In previous lessons you wrote JavaScript programs that collected user input and produced an

output page. These programs executed statements in a predetermined pattern: asking a user

for data at certain points, and computing results based on the data. Once your program

started, it was in complete control of its execution. It ran to completion and then stopped.

Event driven programs are different. With Web sites it is difficult to know exactly what the

user will do and when. For example, a Web page may present a number of clickable images,

text boxes, and check boxes that the user can choose to click. There are many possible

sequences of clicks that the user can perform. Perhaps he or she will choose to click a link

that shows a new page, then return later to the original page and click a button that submits

data to a remote server. Or perhaps the user will instead click an image that starts an applet.

On large, complex pages there are many possibilities presented to the user.

It is very difficult, if not impossible, to write code that predicts the sequence of actions the

user might select in such a situation. Instead, it is far simpler to write a separate piece of code

for each of the possible things that the user can do. When the user chooses an action, such as

clicking a button, the corresponding piece of code can be executed. In this way, the code is

set up to respond to the actions of the user, instead of running to completion by itself. The

control of the order of execution is in the hands of the user, rather than the program.

Page 3: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 3

Copyright © August 2002 Pace University

Events and Event Handlers

In event driven Web pages, user actions determine the course of code execution. User actions

are events, and the separate sections of code that responds to events are called event

handlers. An event handler is a predefined JavaScript keyword. It is a special attribute that is

associated with hyperlinks, buttons, and other elements of a Web page. Event handlers

always begin with the word on. Examples of event handlers include onClick, onMouseOver,

and onMouseOut.

Event driven JavaScript waits for your Web page visitor to take a particular action, such as

placing the mouse arrow over an image, before it reacts by executing code. The key to coding

event driven JavaScript is to know the names of events and how to use them.

It is important to understand that events happen to a particular button, link, or other

component on the Web page. You can say that an event belongs to that component. This

should make sense to you. If you click the mouse on a blank part of a Web page, there is no

response. If you click a button on the page, then that button’s event handler executes.

So where do you insert this event handler code? Since an event belongs to a Web page

component, its event handler code should be placed with the component itself. In this lesson,

you will write event handlers for hyperlinks and buttons, and you will see that the event

handler code is part of the definition of the links and buttons you include in your Web page.

onClick Event Handlers and Links

This first example of an event handler is part of a hyperlink. You have been clicking

hyperlinks since the first day you saw a Web page. The default action of a hyperlink is to go

to a new Web site. Using the JavaScript event handler onClick, this code instead produces an

alert message.

<html>

<head>

<title>onClick and Hyperlinks</title>

</head>

<body>

<h1>Example of an onClick Event Handler</h1>

<a href="#" onClick = "alert('This is what it does!');">Click this

link!</a>

</body>

</html>

Page 4: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-4| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

When you run this code and click the link, and the following message appears:

All the relevant code for the event handler is in line 9, where the link is defined. The symbol

“#” is HTML code that tells the browser to stay on this page. Next is the keyword onClick.

Notice it is inside the anchor tag, and there are no script tags. They are not needed with event

handlers.

The syntax for the onClick event handler is as follows:

Syntax:

onClick=”JavaScript statement(s);”

Page 5: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 5

Copyright © August 2002 Pace University

The event handler code you write is placed inside a pair of quote marks. Let‟s take a closer

look at the code for this particular event handler:

onClick = "alert('This is what it does!');"

Notice there are two sets of quotes. The outer set of double quotes serves as delimiters

(boundaries) for the event handler. Nested inside the alert method is another pair of single

quotes. These serve as delimiters for the message string. You often have to nest quotes with

event handlers, and it is easy to make a mistake that causes your code not to run.

Follow these rules when using quotes with event handlers:

alternate pairs of double quote marks with single quote marks

inner quote marks must be paired up (nested) within the enclosing quotes. For

example:

“This is an error „caused by overlapping” quote marks.‟

should be like this:

“This is the „right way‟ to nest quotes inside each other.”

Also notice that the alert statement ends with a semicolon. This enables you to add additional

JavaScript code after the alert, performing multiple actions in response to a click event rather

than a single JavaScript statement. For example:

<html>

<head>

<title>Multiple Alerts</title>

</head>

<body>

<a href="#" onClick="alert('one'); alert('two'); alert('three');

alert('four'); alert('five');">Click this link</a>

</body>

</html>

This link‟s onClick event handler produces five alert messages. This is possible because each

alert is separated by a semi-colon. But it should be apparent that this method quickly gets

inconvenient and messy. In the next lesson you will learn a better way to write event handlers

with complex logic and multiple statements. You will learn how to write using a function that

handles the event. Since a function is a separate section of code, it is easier to put multiple

event handler statements within a function.

Page 6: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-6| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

onClick Event Handlers for Buttons

Button are elements of HTML forms. You declare a button by including an input tag with

type set to button within form tags. Buttons also have onClick event handlers with the same

syntax as links.

Here is an example of JavaScript code that displays an alert message when the user clicks the

button:

<html>

<head>

<title>onClick and Buttons</title>

</head>

<body>

<form>

<input type="button" value="Click Me" onClick="alert('You clicked a button');">

</form>

</body>

</html>

Here is what the output looks like:

Page 7: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 7

Copyright © August 2002 Pace University

Notice the syntax for the onclick event handler is the same as for hyperlinks. You need to

include the keyword onClick within the definition for the button. You need to enclose the

code for the event handler within double quotes. You need to use single quotes for any

interior quotes. You should also terminate statements with a semi-colon to allow you to add

extra statements. Now that you see how the click event works, we will explore events and

event handlers associated with moving the mouse.

Mouse Events

Links can respond to other events, such as those triggered when the user moves the mouse.

Two event handlers you will learn about are onMouseOver and onMouseOut. Moving the

mouse arrow over a link triggers onMouseOver. The onMouseOver event handler has a

syntax similar to the onClick method:

Syntax:

onMouseOver=”JavaScript statement(s);”

Just like the onClick event handler, you need to insert this code in the definition for the link.

You also need to enclose the JavaScript statements within quotes marks. Here is a sample

onMouseOver event handler for a link:

<a href=”#” onMouseOver = “alert(„You are over this link‟);”>Mouse Over

Link</a>

The onMouseOut event is triggered when the mouse arrow moves off a link. Here is the

syntax for onMouseOut:

Syntax:

onMouseOut=”JavaScript statement(s);”

Page 8: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-8| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

Here is a example for onMouseOut:

<a href=”#” onMouseOut = “alert(„You are now off this link‟);”>Mouse Out

Event</a>

Mouse Event and the Window Status Bar

A common functionality for onMouseOver is to use it to write a message in the window

status bar, the thin grey bar at the very bottom of your browser window.

JavaScript code can change the status bar by accessing the window object, a JavaScript built

in object. You have already used the document object and document.write to display text;now

you will learn how to use the window object. The built-in JavaScript window object has

many useful properties, including the status property. By assigning a value to the status

property, you change what is displayed in the status bar in your browser. Here is an example:

window.status = “Welcome to CIS101!”

This code displays the message “Welcome to CIS101” in the status bar. Remember the dot

notation that is required when accessing parts of an object. This notation, window.status,

means that status is a property of the window object.

Here is a program that changes the status bar using onMouseOver:

<html>

Page 9: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 9

Copyright © August 2002 Pace University

<head>

<title>onMouseOver Example</title>

</head>

<body>

<center>

<h1> onMouseOver and Status Bar</h1>

<a href="#" onMouseOver="window.status='over first';

return true;">First</a>

<p>

<a href="#" onMouseOver="window.status='over second';

return true;">Second</a>

<p>

<a href="#" onMouseOver="window.status='over third';

return true;">Third</a>

<p>

</center>

</body>

</html>

Notice the return true statement after the window.status command. This extra code is needed

to keep the new message visible. When the user places the mouse arrow over one of these

Page 10: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-10| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

links, it triggers the onMouseOver event handler. The statement “return true” prevents the

URL from appearing in the status bar (this is the default behavior). If you do not include

“return true”, then your message will be briefly displayed then quickly replaced by the URL.

You will use these two events, onMouseOver and onMouseOut, together in the lab to

produce an image swap.You are not required to use them together. You can use each one by

itself, or even combine them with the onClick event handler.

Here is a link with all three event handlers:

<a href=”#” onMouseOver = “window.status = „now you are over‟;”

onMouseOut = “window.status = „now you are out‟;”

onClick = “alert(„now you have clicked‟);”>

Link With Three Event Handlers</a>

You also have onMouseOver and onMouseOut events associated with buttons. Here is a

similar example coded for a button:

<form>

<input type="button" value="click" onMouseOver = "alert('over');"

onMouseOut=”alert(„out‟);” onClick = “alert(„click‟);”>

</form>

Even with these simple events, you now have a lot of power in your hands. Users are

constantly moving the mouse. To see how often this event handler is used, just visit a few

Web sites and notice what happens when you move the mouse. Does the appearance of the

page change? What happens to the status bar? In the lab you will shortly learn to write the

code that carries out these things yourself.

Page 11: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 11

Copyright © August 2002 Pace University

In the Lab

This week in the lab you will use JavaScript to write event-driven programs, responding to

the click event, and the onMouseOn and onMouseOver events.

Start 1st Page 2000 and begin a new HTML document. Save the file giving it the name

lesson0501.html. For the exercises in this lesson, script tags are not needed.

Now type in exactly the following code:

<html>

<head>

<title>Lesson 05: Introduction to Events</title>

</head>

<body>

<center>

<h1>Click your favorite color:</h1>

<a href="#" onClick="document.bgColor='red';">Red</a>

<p>

<a href="#" onClick="document.bgColor='blue';">Blue</a>

<p>

<a href="#" onClick="document.bgColor='green';">Green</a>

<p>

</center>

</body>

</html>

When you run this code, it allows you to select different background colors for your

document. Run your program and test that each color works properly. If you have problems,

confirm that you have double quotes defining both the beginning and end of the onClick

event handler, and that you use single quotes for the colors. Be especially careful about

spelling event handlers and property names. Pay close attention to what letters are upper case

and what letters are lower case.

Let‟s look in more detail at the code that changes the background color:

onClick="document.bgColor='red';"

Page 12: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-12| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

bgColor is a property of the document object, and it stands for background color. It is the

JavaScript equivalent of the <body bgcolor> tag, although in JavaScript the property name is

case sensitive. The other body tag attributes also have JavaScript equivalents. Here is a table

of the properties and a description of what they do:

document property description

fgColor color of text

linkColor color of link the user has not yet visited

vlinkColor color of link user has already visited

alinkColor color of link user clicks

You can use JavaScript statements to change the value of these properties as well. Consider

the following:

document.fgColor = „yellow‟;

This code changes the color of the text to yellow. The difference between using HTML to set

these values and using JavaScript is that you can allow the user to select, through events and

event handlers, the way the page is displayed. This makes pages containing JavaScript

dynamic and interactive compared with those created only with HTML.

Student Modifications

Refer to Appendix C and select three additional colors. Add three new links along

with onClick event handlers that change the bgColor property to the new colors. Test

the added colors to ensure they are working properly.

For each color (you should now have six), select a contrasting value for the fgColor

property (document.fgColor). The fgColor property controls the color of the text.

Insert a second statement for each onClick event handler changing the fgColor

property to a selected contrasting color. Be very careful adding this additional

statement. Be sure that the first statement ends with a semi-colon and that you

terminate the entire event handler with closing double quotes. Here is a sample link

that sets the bgColor property to red and the fgColor property to yellow:

<a href="#" onClick="document.bgColor='red';

document.fgColor='yellow';">Red</a>

Page 13: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 13

Copyright © August 2002 Pace University

Run your code and experiment with your color combinations. Select some that look nice

together. Also try to get find a worst possible combination. What happens when bgColor and

fgColor are the same? Save your file with its modifications.

The onClick Event Handler and Buttons

Now you will learn to use the click event with buttons.

Start a new html document, add the script tags, and save it as lesson0502.html Now type in

exactly the following code:

<html>

<head>

<title>Click Event With Buttons</title>

</head>

<body>

<h1>Click the button to see the greeting</h1>

<center>

<form>

<input type="button" value="Hello" onClick="alert(„Welcome to

CIS101‟);">

<input type="button" value="Goodbye " onClick="alert(„So long, come back

soon!‟);">

</form>

</center>

</body>

</html>

After you have entered this code, test both buttons to ensure they work properly. Then add a

third message of your own choice.

Swapping Images With Mouse Events

A common use of mouse events is for swapping images. The following code swaps a red

arrow for a blue arrow as you move the mouse over a link. Save your earlier work and begin a

new Web document and save it with the name lesson0503.html. Obtain from your instructor

the two image files needed, redArrow.gif and blueArrow.gif, and save them in the same

folder as your HTML document lesson0503.html.

Now type in the following code:

Page 14: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-14| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

<html>

<head>

<title>Creating A Simple Rollover</title>

</head>

<body bgcolor=”white”>

<h1>Creating A Simple Rollover</h1>

<p>

<h2>Roll your mouse on top of the blue arrow and then away from it and

watch the arrow color change!</h2>

<center>

<a href="#" onMouseOver="document.arrow.src='blueArrow.gif';"

onMouseOut="document.arrow.src='redArrow.gif';">

<img src="blueArrow.gif" width="300" height="82" border="0"

name="arrow"></A>

</center>

</body>

</html>

After entering this code, try it out. You should see the arrow change from red to blue as you

move the mouse arrow over and away from the link. If it is not working properly, check for

the common causes of errors:

mis-spelled keywords – be sure to check upper and lower case letters

mis-matched quote marks, you need double quotes for the event handler, single

quotes for the image file

mis-spelling the image file name

the image file not in the same folder as your html file

After you have the code working, read this section that explains how it works. Even though

this code swaps two images, there is only one image tag in above code. Here is how it works.

Before you can use JavaScript to swap an image, you first have to assign that image a name.

Notice the following code inside the image tag:

name=”arrow”

This assigns the name arrow to the image. The code that actually swaps the image is in the

event handlers:

Page 15: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 15

Copyright © August 2002 Pace University

<a href="#" onMouseOver="document.arrow.src='blueArrow.gif';"

onMouseOut="document.arrow.src='redArrow.gif';">

Notice the syntax document.arrow.src. This is dot notation, once again. It means that arrow is

part of document, and src (source) is part of arrow. The swap is executed by changing the

source property of the arrow image that is part of the document. If the mouse is over the link,

the arrow is blue. If the mouse arrow moves off the link, the arrow is red.

Once you have this code working, try it out with other pairs of images. You can also add

another statement to the event handlers to change the bgcolor property when you change the

image.

Page 16: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-16| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

Key Terms and Definitions

event-driven programming – programming method used to create interactive Web

pages. Event driven programming executes code in response to user actions.

event - action by the user, such as clicking a mouse, that triggers a response from a Web

page.

event handler - code that a Web page executes in response to an event by the user.

onClick event handler - JavaScript keyword that is used in code to define how a Web

page responds to a click event intiated by a user.

onMouseOver event handler – JavaScript keyword that is used in code to define how a

Web page responds to the event triggered when the user places the mouse arrow over a

link.

onMouseOut event handler - JavaScript keyword that is used in code to define how a

Web page responds to the event triggered when the user places the mouse arrow away

from a link.

window.status - status is a property of the JavaScript built-in object window. It controls

what is displayed in the browser‟s status bar.

document.bgColor - bgColor is a property of the JavaScript built-in object document. It

controls the background color of the page displayed by the browser.

document.fgColor - fgColor is a property of the JavaScript built-in object document. It

control the foreground color of the page displayed by the browser. The foreground color

controls the color of any text displayed.

Lesson 5 Summary

In Lesson 5 you learned that event-driven Web pages respond to user actions, and allow

the user to control the order of program execution through the use of events and event

handlers. You learned how to write code for the onClick event handler for both

hyperlinks and buttons. You learned how to write the onMouseOver and onMouseOut

event handlers as well. You used these events to allow the user to alter the appearance of

the page by changing the background color, the foreground color, and the contents of the

status bar. Finally you learned to perform an image swap using mouse events with a

hyperlink.

Page 17: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 17

Copyright © August 2002 Pace University

Lesson 5 Exercises

5_01. The following table lists the distance from the sun to the planets in our solar system.

Planet Mean Distance From

Sun (millions of miles)

Mercury 36.0

Venus 67.1

Earth 92.9

Mars 141.5

Jupiter 483.5

Saturn 886.7

Uranus 1782.7

Neptune 2794.3

Pluto 3666.1

Create a Web page and add nine buttons to your page, one for each planet. Remember you

need to use the form tags when using buttons. Set the caption of each button to a name of a

planet (i.e. value= “Mars”). When the user clicks a planet, display an alert message with its

distance from the sun.

5_02. Remember that HTML allows an image to act as a hyperlink through the following

syntax:

<a href=”some link here”><img src=”somefile.gif” border=”0”></a>

If you use this code to turn an image into a link, the image can now respond to mouse events.

Create a Web page and include a picture of yourself. Turn your picture into a link using the

syntax above. Use the stationary link syntax (href=“#”). When the mouse arrow goes over

your picture, use the onMouseOver event handler to display an alert box with the message

“Get that mouse arrow off my face!”

Page 18: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

5-18| Lesson 5: Introduction to Events

Copyright © August 2002 Pace University

5_03. The following code uses the onMouseOver event handler to write to the status bar:

<html>

<head>

<title>onMouseOver Example</title>

</head>

<body>

<center>

<h1> onMouseOver and Status Bar</h1>

<a href="#" onMouseOver="window.status='over first';

return true;">First</a>

<p>

<a href="#" onMouseOver="window.status='over second';

return true;">Second</a>

<p>

<a href="#" onMouseOver="window.status='over third';

return true;">Third</a>

<p>

</center>

</body>

</html>

If you run this code and place your mouse arrow over “First,” the status bar changes to “over

first.” However, when you move the mouse arrow off the link, the status bar still displays the

now outdated message. To fix this you need to reset the status bar to blank („ ‟) when the

mouse arrow is moved away from the link. Add the event handler onMouseOut that sets

window.status equal to blank ( „ ‟ ). You will need to use two single quotes in order to do

this, i.e.

onMouseOut=”window.status=' ';”

5_04. Another interesting property of the window object is location. You can point the

window to a new Web page by setting a new value to the location property, i.e. the code

window.location='http://cnn.com'

connects this window to the Web site for CNN.

Find three or four Web pages related to each other. For example, find the Web sites of four

news organizations, like www.cnn.com, and www.nytimes.com. Create a Web page and add

three or four buttons to the page. Use each button to connect to a different news service Web

site by altering the window.location property in each button‟s onClick event handler.

Page 19: Lesson 5: Introduction to Eventscsis.pace.edu/.../lesson05.pdfclicking a button, the corresponding piece of code can be executed. In this way, the code is In this way, the code is

JavaScript 101 | 5- 19

Copyright © August 2002 Pace University