JavaScript/Event Handling

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Changing Element Styles Index Next: W3C Event Handlers

Event Handlers[edit]

An event occurs when something happens in a browser window. The kinds of events that might occur are due to:

  • A document loading
  • The user clicking a mouse button
  • The browser screen changing size

When a function is assigned to an event handler, that function is run when that event occurs.

A handler that is assigned from a script used the syntax '[element].[event] = [function];', where [element] is a page element, [event] is the name of the selected event and [function] is the name of the function that occurs when the event takes place.

For example:

document.onclick = clickHandler;

This handler will cause the function clickHandler() to be executed whenever the user clicks the mouse anywhere on the screen. Note that when an event handler is assigned, the function name does not end with parentheses. We are just pointing the event to the name of the function. The clickHandler function is defined like this:

function clickHandler(evt) {
  //some code here
}

By convention the event is represented by the variable 'evt'. In some browsers the event must be explicitly passed to the function, so as a precaution it's often best to include a conditional to test that the evt variable has been passed, and if it hasn't then to use an alternative method that works on those other browsers:


function clickHandler(evt) {
    evt = evt || window.event;
    //some code here
}

Elements within a document can also be assigned event handlers. For example:

document.getElementsByTagName('a')[0].onclick = linkHandler;

This will cause the linkHandler() function to be executed when the user clicks the first link on the page.

Keep in mind that this style of handler assignment depends on the link's position inside the page. If another link tag is added before this one, it will take over the handler from the original link. A best practice is to maintain the separation of code and page structure by assigning each link an identifier by using the id attribute.

<a id="faqLink" href="faq.html">Faq</a>

A handler assignment can then work regardless of where the element is positioned.

document.getElementById('faqLink').onclick = linkHandler;

Events are actions that can be detected by JavaScript, and the event object gives information about the event that has occurred. Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. Events are normally used in combination with functions, and the function will not be executed before the event occurs! JavaScript event handlers are divided into two types:

  1. Interactive event handlers- depends on user interactin with the HTML page ex. Clicking a button
  2. Non-Interactive event handlers-does not need user interaction. Ex. onload

Event Attributes[edit]

Below is the event attributes that can be inserted into different HTML elements to define event actions. IE: Internet Explorer, F: Firefox, O: Opera, W3C: W3C Standard.

Attribute The event occurs when... IE F O W3C
onblur An element loses focus 3 1 9 Yes
onchange The content of a field changes 3 1 9 Yes
onclick Mouse clicks an object 3 1 9 Yes
ondblclick Mouse double-clicks an object 4 1 9 Yes
onerror An error occurs when loading
a document or an image
4 1 9 Yes
onfocus An element gets focus 3 1 9 Yes
onkeydown A keyboard key is pressed 3 1 No Yes
onkeypress A keyboard key is pressed
or held down
3 1 9 Yes
onkeyup A keyboard key is released 3 1 9 Yes
onload A page or image has
finished loading
3 1 9 Yes
onmousedown A mouse button is pressed 4 1 9 Yes
onmousemove The mouse is moved 3 1 9 Yes
onmouseout The mouse is moved
off an element
4 1 9 Yes
onmouseover The mouse is moved
over an element
3 1 9 Yes
onmouseup A mouse button is released 4 1 9 Yes
onresize A window or frame is resized 4 1 9 Yes
onselect Text is selected 3 1 9 Yes
onunload The user exits the page 3 1 9 Yes

Mouse/Keyboard Attributes:

Property Description IE F O W3C
altKey Returns whether or not the "ALT"
key was pressed when an event
was triggered
6 1 9 Yes
button Returns which mouse button was
clicked when an event was triggered
6 1 9 Yes
clientX Returns the horizontal coordinate of
the mouse pointer when an event was triggered
6 1 9 Yes
clientY Returns the vertical coordinate of the
mouse pointer when an event was triggered
6 1 9 Yes
ctrlKey Returns whether or not the "CTRL" key
was pressed when an event was triggered
6 1 9 Yes
metaKey Returns whether or not the "meta" key
was pressed when an event was triggered
6 1 9 Yes
relatedTarget Returns the element related to the
element that triggered the event
No 1 9 Yes
screenX Returns the horizontal coordinate of the
mouse pointer when an event was triggered
6 1 9 Yes
screenY Returns the vertical coordinate of the mouse
pointer when an event was triggered
6 1 9 Yes
shiftKey Returns whether or not the "SHIFT" key was
pressed when an event was triggered
6 1 9 Yes

Other Event Attributes:

Property Description IE F O W3C
bubbles Returns a Boolean value that indicates
whether or not an event is a bubbling event
No 1 9 Yes
cancellable Returns a Boolean value that indicates
whether or not an event can have
its default action prevented
No 1 9 Yes
currentTarget Returns the element whose event
listeners triggered the event
No 1 9 Yes
Returns the element that triggered the event No 1 9 Yes
timeStamp Returns the time stamp, in milliseconds
from the epoch (system start or event trigger)
No 1 9 Yes

Standard event handlers[edit]

Attribute Trigger
onabort Loading of image was interrupted
onblur Element loses focus
onchange Element gets modified
onclick Element gets clicked
ondblclick Element gets double clicked
onerror An error occurred loading an element
onfocus An element received focus
onkeydown A key was pressed when an element has focus
onkeypress A keystroke was received by the element
onkeyup A key was released when the element has focus
onload An element was loaded
onmousedown The mouse button was pressed on the element
onmousemove The mouse pointer moves while inside the element
onmouseout The mouse pointer was moved outside the element
onmouseover The mouse pointer was moved onto the element
onmouseup The mouse button was released on the element.
onreset The form's reset button was clicked
onresize The containing window or frame was resized
onselect Text within the element was selected
onsubmit A form is being submitted
onunload The content is being unloaded (e.g. window being closed)
onscroll The user scrolls (in any direction and with any means).

Event Handlers as HTML attributes[edit]

In HTML, JavaScript events can be included within any specified attribute - for example, a body tag can have an onload event:

<body onload="alert('Hello world!');">

The content of the HTML event attributes is JavaScript code that is interpreted when the event is triggered, and works very similarly to the blocks of JavaScript. This form of code is used when you want to have the JavaScript attached directly to the tag in question.

This type of technique is called inline JavaScript, and can be seen as being a less desirable technique than other unobtrusive JavaScript techniques that have previously been covered. The use of inline JavaScript can be considered to be similar in nature to that of using inline CSS, where HTML is styled by putting CSS in style attributes. This is a practice that is best avoided in favour of more versatile techniques.


Previous: Changing Element Styles Index Next: W3C Event Handlers