Events
Events allow you to write JavaScript code that reacts to certain situations. Examples of events include:
The user clicking the mouse button
The Web page loading
A form field being changed
Event Handlers
The Web page loading
A form field being changed
Event Handlers
To allow you to run your bits of code when these events occur, JavaScript provides us with event handlers. All the event handlers in JavaScript start with the word
on
, and each event handler deals with a certain type of event. Here's a list of all the event handlers in JavaScript, along with the objects they apply to and the events that trigger them:Event handler | Applies to: | Triggered when: |
onAbort | Image | The loading of the image is cancelled. |
onBlur | Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window | The object in question loses focus (e.g. by clicking outside it or pressing theTAB key). |
onChange | FileUpload, Select, Text, TextArea | The data in the form element is changed by the user. |
onClick | Button, Document, Checkbox, Link, Radio, Reset, Submit | The object is clicked on. |
onDblClick | Document, Link | The object is double-clicked on. |
onDragDrop | Window | An icon is dragged and dropped into the browser. |
onError | Image, Window | A JavaScript error occurs. |
onFocus | Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window | The object in question gains focus (e.g. by clicking on it or pressing the TAB key). |
onKeyDown | Document, Image, Link, TextArea | The user presses a key. |
onKeyPress | Document, Image, Link, TextArea | The user presses or holds down a key. |
onKeyUp | Document, Image, Link, TextArea | The user releases a key. |
onLoad | Image, Window | The whole page has finished loading. |
onMouseDown | Button, Document, Link | The user presses a mouse button. |
onMouseMove | None | The user moves the mouse. |
onMouseOut | Image, Link | The user moves the mouse away from the object. |
onMouseOver | Image, Link | The user moves the mouse over the object. |
onMouseUp | Button, Document, Link | The user releases a mouse button. |
onMove | Window | The user moves the browser window or frame. |
onReset | Form | The user clicks the form's Reset button. |
onResize | Window | The user resizes the browser window or frame. |
onSelect | Text, Textarea | The user selects text within the field. |
onSubmit | Form | The user clicks the form's Submit button. |
onUnload | Window | The user leaves the page. |
Using the Event Handlers
To use an event handler, you usually place the event handler name within the HTML tag of the object you want to work with, followed by
Example
Example
Example
Example
Example
Example
Example
="
SomeJavaScriptCode"
, whereSomeJavaScriptCode is the JavaScript you would like to execute when the event occurs.For example:
Although the original JavaScript event handler name contains
capital letters (
itself (
specification (which we do!). All element names and attributes must be
lowercase in XHTML.
The Event Object
<input type="submit" name="clickme"
value="Click Me!" onclick="alert('Thank You!')"/>Although the original JavaScript event handler name contains
capital letters (
"onClick"
), you should use all lowercase in the HTML itself (
"onclick"
) if you want your markup to follow the XHTML specification (which we do!). All element names and attributes must be
lowercase in XHTML.
The Event Object
The
Event
object is created automatically whenever an event occurs. There are a number of properties associated with the Event
object that can be queried to provide additional information about the event:Event.data
Used by the
onDragDrop
event. Returns an array of URLs of dropped objects.Event.height
Stores the height of the window or frame containing the object connected with the event.
Event.modifiers
Returns a string listing any modifier keys that were held down during a key or mouse event. The modifier key values are:
ALT_MASK
, CONTROL_MASK
,SHIFT_MASK
and META_MASK
.Event.pageX
Event.pageY
These properties hold the X and Y pixel coordinates of the cursor relative to the page, at the time of the event.
Event.screenX
Event.screenY
These properties hold the X and Y pixel coordinates of the cursor relative to the screen, at the time of the event.
Event.target
Returns a string representing the object that initiated the event.
Event.type
Returns a string representing the type of the event (keypress, click, etc).
Event.which
Returns a number representing the mouse button that was pressed (1=left, 2=middle, 3=right) or the ASCII code of the key that was pressed.
Event.width
Stores the width of the window or frame containing the object connected with the event.
Event.x
Event.y
These properties hold the X and Y pixel coordinates of the cursor relative to the layer connected with the event or, for the
onResize
event, the width and height of the object after it was resized. (You can also use event.layerX
and event.layerY
, which do the same thing.) - Some examples of event Handlers
In this section, we'll look at a few of the more commonly used event handlers, and examine how they can be used.
onChange
onChange
is commonly used to validate form fields or to otherwise perform an action when a form field's value has been altered by the user. The event handler is triggered when the user changes the field then clicks outside the field or uses the TAB key (i.e. the object loses focus).Example
This example code ensures that you type in both your first and your last names. It will bring up an alert box and refocus the text box field if you only type one word into the text box.
Please enter your name: <input type="text" name="your_name" onchange="validateField(this)"/>
<script type="text/javascript">
function validateField ( fieldname )
{
if ( ( fieldname.value ) &&
( ! fieldname.value.match ( " " ) ) )
{
alert ( "Please enter your first and last names!" );
fieldname.focus ( );
}
}
</script>
onClick
The
onClick
handler is executed when the user clicks with the mouse on the object in question. Because you can use it on many types of objects, from buttons through to checkboxes through to links, it's a great way to create interactive Web pages based on JavaScript.Example
In this example, an alert box is displayed when you click on the link below.
<a href="#" onclick="alert('Thanks!')">Click Me!</a>
OnFocus
onFocus
is executed whenever the specified object gains focus. This usually happens when the user clicks on the object with the mouse button, or moves to the object using the TAB key. onFocus
can be used on most form elements.Example
This example text box contains the prompt "Please enter your email address" that is cleared once the text box has focus.
<input type="text" name="email_address"
size="40" value="Please enter your email address"
onfocus="this.value=''"/>
onKeyPress
You can use
onKeyPress
to determine when a key on the keyboard has been pressed. This is useful for allowing keyboard shortcuts in your forms and for providing interactivity and games.Example
This example uses the
onKeyPress
event handler for the Window
object to determine when a key was pressed. In addition, it uses the which
property of the Event
object to determine the ASCII code of the key that was pressed, and then displays the pressed key in a text box. If event.which
is undefined it uses event.keyCode
instead (Internet Explorer uses event.keyCode
instead of event.which
).
<html>
<body onkeypress = "show_key(event.which)">
<form method="post" name="my_form">
The key you pressed was:
<input type="text" name="key_display" size="2"/>
</form>
<script type="text/javascript">
function show_key ( the_key )
{
if ( ! the_key )
{
the_key = event.keyCode;
}
document.my_form.key_display.value
= String.fromCharCode ( the_key );
}
</script></body></html>
onLoad
The
onLoad
event handler is triggered when the page has finished loading. Common uses of onLoad
include the dreaded pop-up advertisement windows, and to start other actions such as animations or timers once the whole page has finished loading.Example
This simple example displays an alert box when the page has finished loading:
<html>
<body onload = "alert('Thanks for visiting my page!')">
My Page
</body>
</html>
onMouseOut
, onMouseOver
Example
Here's a simple example that alters the value of a text box depending on whether the mouse pointer is over a link or not.
<form>
<input type="text" id="status" value="Not over the link"/>
<br>
<a href="" onmouseover="document.getElementById('status').value='Over the link'"
onmouseout="document.getElementById('status').value='Not over the link'">Move
the mouse over me!</a>
</form>
onSubmit
The onSubmit event handler, which works only with the
Form
object, is commonly used to validate the form before it's sent to the server. Example
This example asks you to confirm whether you want to submit the form or not when you click on the button. It returns
true
to the event handler if the form is to be submiited, and false
if the submission is to be cancelled.
<form onsubmit="return confirm('Are You Sure?')" action="">
<input type="submit" name="submit" value="Submit"/>
</form>
No comments:
Post a Comment