Friday, June 22, 2012

Java Script Tutorial 16 : JavaScript Events

Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Following are some events we use in javascript.
  • A mouse click
  • A web page loading
  • Mousing over
  • Selecting an input field
  • Submitting an HTML form
  • A keystroke
Details of some some events are below.


onLoad and onUnload :
The onLoad and onUnload events are triggered when the user enters or leaves the page. The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.


Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.


onFocus, onBlur and onChange :
The onFocus, onBlur and onChange events are often used in combination with validation of form fields. In following example the validateEmail() function will be called whenever the user changes the content of the field.


<input type="text" size="30" id="email" onchange="validateEmail()" />


onSubmit :
The onSubmit event is used to validate ALL form fields before submitting it. In following example, the validateForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function validateForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled.


<form method="post" action="mypage.htm" onsubmit="return validateForm()">


onMouseOver :
The onmouseover event can be used to trigger/call a function when the user mouses over an HTML element.

No comments:

Post a Comment