Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Events

Many different types of events take place in browsers. JavaScript provides access to a number of events that would be useful to you, such as the click event, which occurs when the left mouse button is pressed once. Most of the events correspond to an HTML element that a user can see and manipulate such as a button or a check box. Table 3.6 contains a list of events that can be captured by JavaScript and the JavaScript object with which the event is associated.

Table 3.6  Browser Events

Event

Object

Occurs When...

Abort

Image

images do not finish loading

Blur

Button, Checkbox, FileUpload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, Window

input focus is removed from the element

Change

FileUpload, Select, Text, Textarea

value of the element is changed

Click

Area, Button Checkbox, Document, Link, Radio, Reset, Submit

element is clicked

DblClick

Area, Document, Link

mouse button is double-clicked

DragDrop

Window

object is dropped onto browser Window

Error

Image, Window

there is an error in the page or image

Focus

Button, Checkbox, FileUpload, Frame, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, Window

input focus is given to element

KeyDown

Document, Image, Link, Textarea

key is depressed

KeyPress

Document, Image, Link, Textarea

key pressed and held down

KeyUp

Document, Image, Link, Textarea

key is released

Load

Document, Image, Layer, Window

page is loaded into browser

MouseDown

Button, Document, Link

left mouse button is depressed

MouseMove

Window

mouse cursor is moved

MouseOut

Area, Layer, Link

mouse cursor is moved out of the element's bounds

MouseOver

Area, Layer, Link

mouse is moved over element

MouseUp

Button, Document, Link

mouse button is released

Move

Frame

element is moved

Reset

Form

form is reset

Resize

Frame, Window

browser window is resized

Select

Text, Textarea

input field is selected

Submit

Form

form is submitted

Unload

Window

current page is unloaded

Of the events covered in the previous table, the Error and Abort events deserve a little more explanation because they are not as straightforward as the rest.

The Error event is used by the Window and Image objects to indicate that an error occurred while either loading an HTML page or loading an image. This type of error will result in the browser issuing a JavaScript syntax error or a runtime error.

The Abort event is used by the Image object to indicate that the loading of an image was aborted. This type of event occurs often because users become impatient waiting for a large image to load, so they stop the image load before it completes by clicking the browser's Stop button or clicking a link to another page.

Event Handlers

Now that you know the types of events that JavaScript provides, access to them is just a matter of capturing those events. Events are captured using event handlers. By assigning a function or a single line of JavaScript code to an object's event handler, you can capture an event and take action. Table 3.7 shows all the event handlers and the events they are associated with.

Table 3.7  Event Handlers

Event

Event Handler

Abort

onAbort

Blur

onBlur

Change

onChange

Click

onClick

DblClick

onDblClick

DragDrop

onDragDrop

Error

onError

Focus

onFocus

KeyDown

onKeyDown

KeyPress

onKeyPress

KeyUp

onKeyUp

Load

onLoad

MouseDown

onMouseDown

MouseMove

onMouseMove

MouseOut

onMouseOut

MouseOver

onMouseOver

MouseUp

onMouseUp

Move

onMove

Reset

onReset

Resize

onResize

Select

onSelect

Submit

onSubmit

Unload

onUnload

Capturing Events

Event handlers can be defined in one of two ways. The first and most common way is to define the handler inside HTML tags much in the same way HTML tag properties are assigned. For example, to display an alert box when a button is clicked, simply assign a JavaScript alert box to the onClick event handler inside the button's HTML tag as follows:

<form name="myForm">
<input
  type="button"
  name="myButton"
  value="Press Me"
  onClick="alert('myButton was pressed')">
</form>

Anytime myButton is clicked an alert box will be displayed that tells the user that "myButton was pressed". Remember that not all events are associated with every object. To see what events and event handlers are available to a particular object, look for the object in Chapter 8, "Client-Side."

The second way to define event handlers is to define the handler inside JavaScript code using dot notation. Listing 3.2 demonstrates how to assign a JavaScript alert box to the onClick event handler using dot notation.

Listing 3.2  Defining Event Handlers Using Dot Notation

<html>
<form name="myForm">
<input type="button" name="myButton" value="Press Me">
</form>

<script type="text/javascript" language="JavaScript">
<!--
document.myForm.myButton.onclick="alert('myButton was pressed')";
//-->
</script>
</html>

In listing 3.2 myButton was initially created using standard HTML tags. Directly after creating the button JavaScript dot notation is used to access the button object and assign an alert box to the onclick handler.

NOTE

Notice that in Listing 3.2 the onclick property was written using a lowercase c rather than an uppercase C as was used when accessing the onClick property via the HTML input tag. This is not a typo! When defining event handlers inside HTML, use the uppercase characters as shown in Table 3.7. When defining event handlers inside JavaScript code using dot notation, the event handlers must not contain any uppercase characters.

Canceling Events

One of the most common uses of event handlers is validation of data entered through an HTML form. For example you might want to verify that a password entered by a user in a password change form is valid before submitting the form to the server. If the password entered by the user is not valid, the user should be notified of the problem and the form should not be submitted. Utilizing the material covered so far, it is easy to capture the Click event of the form's submit button and alert the user of the problems with the password entered. But how do you prevent the event from continuing and the form from being submitted to the server? The Submit event can be canceled by simply returning false in the event handling routine. Listing 3.3 demonstrates how to cancel the form submission.

Listing 3.3  Canceling the Submit Event

<html>
<script type="text/javascript" language="JavaScript">
<!--

function validatePassword()
{
  passwd = document.passwordForm.password.value;

  //Password must be between 3 and 15 characters
  if((passwd.length < 3) || (passwd.length > 15))
  {
    alert("Password must be less than 15 characters but greater than 3!");
    return(false);
  }
}

//-->
</script>

<center>
<h1>Password Change Page</h1>
Please enter your user name and new password.<br>
(Password must be between 3 and 15 characters.)<br><br>
<form name="passwordForm" 
      action="success.html" 
      onSubmit="return validatePassword()">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>
</html>

Not all the event handlers allow you to stop an event from taking place, but some do. Of the events that can be stopped, the value used to stop the event varies. Table 3.8 shows the events that acknowledge return codes and what values to return to cancel the event.

Table 3.8  Event Handler Return Values

Event

Value to Return to Cancel Event

OnClick

false

OnKeyDown

false

OnKeyPress

false

OnMouseDown

false

OnMouseOver

true (prevents URL from appearing in status bar)

onMouseUp

false

onReset

false

onSubmit

false

Invoking Event Handlers

There are times when you might want to explicitly invoke a particular event handler even though no event took place. This is easy to accomplish because the event handlers are essentially pointers to functions stored as a property of an object that should be executed when a particular event occurs. To invoke an event handler, simply use dot notation to execute the event handler as if it were a function. For example, in the following piece of code, we want to alert the user about a sweepstakes when he moves his cursor over the Lamborghini link. We also want to remind him of the sweepstakes when he goes back to the previous page. To do this, the event handler for the Lamborghini link is executed when the user clicks the Previous Page link.

<a href="sweepstakes.html" 
   onMouseOver="alert('Enter our sweepstakes for a chance to win a brand new 
sports car!')">Lamborghini</a><br>
<a href="intro.html" 
   onClick="document.links[0].onmouseover()">Previous Page</a>

Timers

Even though JavaScript does not directly provide an event-driven timer, we will discuss timers in this section because timers should generally be thought of in terms of events. Because JavaScript does not directly provide a timer, it is possible to use the Window object's setInterval() method to serve the same purpose.

NOTE

The setInterval() method is supported in JavaScript 1.2 and higher.

The setInterval() method repeatedly calls a function or evaluates an expression each time a time interval (in milliseconds) has expired. This method continues to execute until the window is destroyed or the clearInterval() method is called.

For example, in Listing 3.4 the setInterval() method is executed when the document opens and begins to call the dailyTask() function every 20,000 milliseconds. The dailyTask() function evaluates the time each time it is called, and when it is 8:00 a.m., the code within the if statement is called, alerting the user and then clearing the interval. When the clearInterval() method is called, setInterval() halts execution.

Listing 3.4  Creating a Timed Event with the setInterval() Method

<html>
<script type="text/javascript" language="JavaSCript">
<!--
  function dailyTask()
  {
    var today = new Date();
    if ((today.getHours() == 8) && (today.getMinutes() == 0))
    {
      alert("It is 8:00 a.m.");
      clearInterval(timerID);
    }
  }
  //Set interval to 20,000 milliseconds
  timerID = setInterval("dailyTask()",20000);

//-->
</script>
</html>

As mentioned earlier the setInterval() method is only available in JavaScript 1.2 and higher. If you need to support an earlier version of JavaScript, you will have to use the setTimeout() method.

The setTimeout() method is usually used to evaluate an expression after a specific amount of time. Unlike the setInterval() method, the setTimeout() method is a one-time process that is not repeated an infinite number of times. Listing 3.5 produces the same result as Listing 3.4, using the setTimeout() method instead of the setInterval() method.

Listing 3.5  Creating a Timed Event with the setTimeout() Method

<html>
<script type="text/javascript" language="JavaScript">
<!--
  function dailyTask()
  {
    var today = new Date();
    if ((today.getHours() == 8) && (today.getMinutes() == 0))
    {
      alert("It is 8:00 a.m.");
    }
  }
  //Set delayed execution of function to 20,000 milliseconds
  setTimeout("dailyTask()",20000);

//-->
</script>
</html>
  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020