Javascript Events and Event Handlers

Events and Event Handlers

Learn all about events in JavaScript, and how you can use them for all sorts of neat tricks.

What are 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

To allow you to run your bits of code when these events occur, JavaScript provides us withevent 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 an event handler

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 ="SomeJavaScriptCode", whereSomeJavaScriptCode is the JavaScript you would like to execute when the event occurs.

For example:


<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_MASKCONTROL_MASKSHIFT_MASKand  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 common 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 (see our tutorial on Form validation with JavaScript) 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>

Please enter your name: 

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>

Click Me!

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. Ifevent.which is undefined it uses event.keyCode instead (Internet Explorer usesevent.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>

Try it out!

onLoad

The onLoad event handler is triggered when the page has finished loading. Common uses ofonLoad 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>

Try it out!

onMouseOutonMouseOver

The classic use of these two event handlers is for JavaScript rollover images (images, such as buttons, that change when you move your mouse over them). We have a tutorial on just this topic called Rollover buttons with JavaScript.

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>

 
Move the mouse over me!

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. In fact we have a whole tutorial on this topic, called Form validation with JavaScript.

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值