Javascript Main Events
OnBlur Event
Def : Fires when the object loses the input focus.
To invoke
• Click the mouse on the document background or another control.
• Use the keyboard to navigate from one object to the next.
• Invoke the blur method when an object has focus.
• Switch focus to a different application or open a second window.
Default action
Switches focus away from the object on which the event is fired.
Remarks
- The onblur event fires on the original object before the onfocus or onclick event fires on the object that is receiving focus. Where applicable, the onblur event fires after the onchange event.
- Use the focus events to determine when to prepare an object to receive or validate input from the user.
- For Internet Explorer 5 and later, the onblur event is asynchronous.
Example
This example shows how to display the name of the object that has lost focus, that is, the object that fires the onblur event
<html<body>
<input type="text" name="txtFName" value="First Name" onblur="alert(event.srcElement.name)">
<input type="text" name="txtLName" value="Last Name"
onblur="alert(event.srcElement.name)">
<input type="text" name="txtPhone" value="Phone"
onblur="alert(event.srcElement.name)">
</body</html>
OnLoad Event
Def : Fires immediately after the client loads the object.
Syntax : <ELEMENT onload = "handler(event);" >
To invoke
Open a document to invoke this event for the document or any object within it.
Remarks
The client loads applications, embedded objects, and images as soon as it encounters the applet, embed, and img objects during parsing. Consequently, the onload event for these objects occurs before the client parses any subsequent objects. To ensure that an event handler receives the onload event for these objects, place the script object that defines the event handler before the object and use the onload attribute in the object to set the handler.
The onload attribute of the body object sets an onload event handler for the window. This technique of calling the window onload event through the body object is overridden by any other means of invoking the window onload event, provided the handlers are in the same script language.
Example
The following example shows how to declare an onload event for a document that is designed to work with multiple browsers and earlier versions of Internet Explorer.
<!doctype html>
<head>
<title>Load Event Sample</title>
<script type="text/javascript">
function doLoad() {
alert( "The load event is executing" );
}
if ( window.addEventListener ) {
window.addEventListener( "load", doLoad, false );
}
else
if ( window.attachEvent ) {
window.attachEvent( "onload", doLoad );
} else
if ( window.onLoad ) {
window.onload = doLoad;
}
</script>
</head>
<body>
<h1>Load Event Sample</h1>
<p>This sample demonstrates how to execute
an event while the document is loading.</p>
</body>
</html>
OnClick
Def : fires when the user clicks the left mouse button on the object.
Syntax : <ELEMENT onclick = "handler(event);" >
To invoke
•Click the object.
•Invoke the click method.
•Press the ENTER key in a form.
•Press the access key for a control.
•Select an item in a combo box or list box by clicking the left mouse button or by pressing the arrow keys and then pressing the ENTER key.
Remarks
If the user clicks the left mouse button, the onclick event for an object occurs only if the mouse pointer is over the object and an onmousedown and an onmouseup event occur in that order. For example, if the user clicks the mouse on the object but moves the mouse pointer away from the object before releasing, no onclick event occurs.
The onclick event changes the value of a control in a group. This change initiates the event for the group, not for the individual control. For example, if the user clicks a radio button or check box in a group, the onclick event occurs after the onbeforeupdate and onafterupdate events for the control group.
If the user clicks an object that can receive the input focus but does not already have the focus, the onfocus event occurs for that object before the onclick event. If the user double-clicks the left mouse button in a control, an ondblclick event occurs immediately after the onclick event.
Although the onclick event is available on a large number of HTML elements, if a document is to be accessible to keyboard users, you should restrict its use to the a, input, area, and button elements. These elements automatically allow keyboard access through the TAB key, making documents that use the elements accessible to keyboard users. For more information, please see the section on writing accessible Dynamic HTML.
Examples
This example uses the event object to gain information about the origin of the click. In addition, it cancels the default action to prevent navigation of anchor elements, unless the SHIFT key is pressed. Normally a Shift+Click opens the target of a link in a new window; however, the script replaces the current document by setting the location of the window object.
<script type="text/javascript">
/* This code cancels the event. If the click occurs in an anchor
and the SHIFT key is down, the document is navigated. */
function clickIt()
{
var e = window.event.srcElement
txtName.value = e.tagName;
txtType.value = e.type;
if ((e.tagName == "A") &
(window.event.shiftKey)) {
window.location.href = e.href;
}
window.event.returnValue = false;
}
</script>
<body onclick="clickIt()">
<p>To follow a link, click while pressing the SHIFT key.</p>
<a href="about:blank">Click Here</a>
<textarea name="txtName"</textarea> <textarea name="txtType"</textarea>
</body>
ondblclick Event
Def : Fires when the user double-clicks the object.
To invoke
Click the left mouse button twice in rapid succession over an object. The user's double-click must occur within the time limit specified by the user's system.
Remarks
The order of events leading to the ondblclick event is onmousedown, onmouseup, onclick, onmouseup, and then ondblclick. Actions associated with any of these events are executed when the ondblclick event fires.
Example
This example uses the ondblclick event to add items to a list box when the user double-clicks in the text box.
HEAD>
<SCRIPT>
function addItem()
{
sNewItem = new Option(txtEnter.value)
selList.add(sNewItem);
}
</SCRIPT>
</HEAD>
<BODY>
<P>Enter text and then double-click in the text box to
add text to the list box.
<INPUT TYPE=text NAME=txtEnter VALUE="Enter_text"
ondblclick="addItem()">
<SELECT NAME=selList SIZE=5</SELECT>
</BODY>
onchange Event
Def : Fires when the contents of the object or selection have changed.
Syntax : <ELEMENT onchange = "handler(event);" >
To invoke
Choose a different option in a select object using mouse or keyboard navigation.
Alter text in the text area and then navigate out of the object.
Default action
Changed text selection is committed.
Remarks
This event is fired when the contents are committed and not while the value is changing. For example, on a text box, this event is not fired while the user is typing, but rather when the user commits the change by leaving the text box that has focus. In addition, this event is executed before the code specified by onblur when the control is also losing the focus.
The onchange event does not fire when the selected option of the select object is changed programmatically.
Example
This example uses the onchange event to retrieve the selected option of a select object.
<body>
<form>
<p>Select a different option in the drop-down list box to trigger the onchange event.
<select name="selTest" onchange="alert('Index: ' + this.selectedIndex
+ '\nValue: ' + this.options[this.selectedIndex].value)">
<option value="Books">Books</option>
<option value="Clothing">Clothing</option>
<option value="Housewares">Housewares</option>
</select> </p>
</form>
</body>
oncopy,oncut,onpaste
Def : Fires on the source element when the user copies[or cut][or paste] the object or selection, adding[taking] it to the system clipboard.
Syntax : <ELEMENT oncopy = "handler(event);" >
<ELEMENT oncut = "handler(event);" >
<ELEMENT onpaste = "handler(event);" >
To invoke
•Right-click to display the shortcut menu and select Copy,[cut][paste]
•Or press CTRL+C[CRTL+V][CRTL+X].
Remarks:
Athough these are the main events used with big applications , you can use as well forepaste,forecut,forcopy where you can invoke related handlers to make use of the result event
onfocus Event
Def :Fires when the object receives focus.
To invoke
•Click an object.
•Use keyboard navigation.
•Invoke the focus method.
•Invoke the setActive method.
Remarks
Note Using the setActive method has no effect on document focus. Using the focus method on an individual element causes the element to gain focus and become the active element.
When one object loses activation and another object becomes the activeElement, the onfocus event fires on the object becoming the activeElement only after the onblur event fires on the object losing activation. Use the focus events to determine when to prepare an object to receive input from the user.
Elements cannot receive focus until the document is finished loading.
For Microsoft Internet Explorer 5.5 and later, focus on a document, and the active element of a document can be managed separately. The synchronous events onactivate and ondeactivate provide better control for managing activation changes.
As of Internet Explorer 5, elebrowserments retain focus within the current history when the user returns to a page. To avoid firing the onfocus event unintentionally for an element when the document loads, invoke the focus method on another element.
As of Internet Explorer 5, you can force elements that do not implicitly receive focus to receive focus by adding them to the document tabbing order using the TABINDEX attribute.
Example
This example uses the onfocus event to make INPUT_text and label objects more accessible. When the INPUT_text object has focus, the onfocus event fires and the backgroundColor, fontSize, and fontWeight properties are changed to give the control more prominence.
...
<style type="text/css">
.normal {
background-color: white;
color: black;
font-weight: normal;
font-size: 8pt;
font-family: Arial;
}
.accessible {
background-color: silver;
font-weight: bold;
font-size: 10pt;
}
</style>
<script type="text/javascript">
function fnSetStyle(){
event.srcElement.className="accessible";
var oWorkLabel=eval(event.srcElement.id + "_label");
oWorkLabel.className="accessible";
}
</script>
<label for="oInput" class="normal" id="oInput_label">Enter some text</label>
<input type="text" class="normal" onfocus="fnSetStyle()" id="oInput">
...
onsubmit Event
Def : Fires when a FORM is about to be submitted.
Syntax :<ELEMENT onsubmit = "handler(event);" >
To invoke
Submit a form using the INPUT TYPE=submit, INPUT TYPE=image, or BUTTON TYPE=submit object.
Remarks
You can override this event by returning false in the event handler. Use this capability to validate data on the client side to prevent invalid data from being submitted to the server. If the event handler is called by the onsubmit attribute of the form object, the code must explicitly request the return value using the return function, and the event handler must provide an explicit return value for each possible code path in the event handler function.
The submit method does not invoke the onsubmit event handler.
Example
This example shows how to use onsubmit on a form. You can return false to prevent the form from being submitted. Note the use of the return keyword in the onsubmit event handler.
<script type="text/javascript">
function displayAnswer ()
{
var question = document.getElementById('question');
var selected = -1;
for (var i=0; i<question.answer.length; i++)
{
if (question.answer[i].checked) {
selected = i;
break;
}
}
if (selected > -1) {
alert("You answered: " + question.answer[selected].value );
return true;
}
alert("Please select an answer.");
return false;
}
</script>
<form id="question" action="#" name="question" onsubmit="return(displayAnswer())">
<p style="font-size: xx-large">Are you a turtle?</p>
<p<label<input name="answer" type="radio" value="YES" />YES</label</p>
<p<label<input name="answer" type="radio" value="NO" />NO</label</p>
<p<label<input name="answer" type="radio" value="MAYBE" />MAYBE</label</p>
<p<input type="submit" value="SUBMIT" /
<input type="reset" value="RESET" /</p>
</form>
onkeypress Event
Def : Fires when the user presses an alphanumeric key.
Syntax : <ELEMENT onkeypress = "handler(event);" >
To invoke
Press any alphanumeric keyboard key.
Default action
Returns a number specifying the Unicode value of the key that was pressed.
Remarks
As of Microsoft Internet Explorer 4.0, the onkeypress event fires and can be canceled for the following keys:
•Letters: A - Z (uppercase and lowercase)
•Numerals: 0 - 9
•Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~
•System: ESC, SPACEBAR, ENTER
Example
This example shows how to retrieve information from the shiftKeyIHTMLEventObj2::shiftKey property of the event object. When the user simultaneously presses the shift key and types a character in the first text field, the value "true" appears in the second text field.
<head>
<script type="text/javascript">
function checkKey()
{
if (window.event.shiftKey) // checks whether the SHIFT key
// is pressed
{
txtOutput.value = "true"; // returns TRUE if SHIFT is pressed
// when the event fires
}
}
</script>
</head>
<body>
<p>Press the SHIFT key while pressing another key.<br>
<input type="text" name="txtEnterValue" onkeypress="checkKey()"> </p>
<p>Indicates "true" if the shift key is used.<br>
<input type="text" name="txtOutput"> </p>
</body>
onkeydown Event
Def : Fires when the user presses a key.
Syntax : <ELEMENT onkeydown = "handler(event);" >
To invoke
Press any keyboard key.
Default action
Returns a number specifying the keyCode of the key that was pressed.
Remarks
You can cancel all keys that fire the onkeydown event in HTML Applications, including most accelerator keys, such as ALT+F4.
As of Microsoft Internet Explorer 5, the event also fires for the following keys:
•Editing: BACKSPACE
•Navigation: PAGE UP, PAGE DOWN
•System: SHIFT+TAB
As of Internet Explorer 5, this event can be canceled for the following keys and key combinations by specifying event.returnValue=false:
•Editing: BACKSPACE, DELETE
•Letters: A - Z (uppercase and lowercase)
•Navigation: PAGE UP, PAGE DOWN, END, HOME, LEFT ARROW, RIGHT ARROW, UP ARROW, DOWN ARROW