< JavaScript

Event Handlers

An event that can be handled is something happening in a browser window, including a document loading, the user clicking a mouse button, the user pressing a key, and the browser screen changing size. When a function is assigned to handle an event type, that function is run when an event of the event type occurs.

An event handler can be assigned in the following ways:

  1. Via an element attribute directly in HTML: <body onload="alert('Hello World!');">
  2. Via JavaScript, by assigning the event type to an element attribute: document.onclick = clickHandler;
  3. Via JavaScript by a direct call to the addEventListener() method of an element.

A handler that is assigned from a script uses 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 is called 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(event) {
  //some code here
}

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 event variable has been passed, and if it hasn't then to use an alternative method that works on those other browsers:


function clickHandler(event) {
  event = event || 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 - depend on user interaction with the HTML page; ex. clicking a button
  2. Non-Interactive event handlers - do not need user interaction; ex. on load

Event Attributes

Below are 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.

AttributeThe event occurs when...IEFOW3C
onblurAn element loses focus319Yes
onchangeThe content of a field changes319Yes
onclickMouse clicks an object319Yes
ondblclickMouse double-clicks an object419Yes
onerrorAn error occurs when loading
a document or an image
419Yes
onfocusAn element gets focus319Yes
onkeydownA keyboard key is pressed31NoYes
onkeypressA keyboard key is pressed
or held down
319Yes
onkeyupA keyboard key is released319Yes
onloadA page or image has
finished loading
319Yes
onmousedownA mouse button is pressed419Yes
onmousemoveThe mouse is moved319Yes
onmouseoutThe mouse is moved
off an element
419Yes
onmouseoverThe mouse is moved
over an element
319Yes
onmouseupA mouse button is released419Yes
onresizeA window or frame is resized419Yes
onselectText is selected319Yes
onunloadThe user exits the page319Yes

Mouse/Keyboard Attributes:

PropertyDescriptionIEFOW3C
altKeyReturns whether or not the "ALT"
key was pressed when an event
was triggered
619Yes
buttonReturns which mouse button was
clicked when an event was triggered
619Yes
clientXReturns the horizontal coordinate of
the mouse pointer when an event was triggered
619Yes
clientYReturns the vertical coordinate of the
mouse pointer when an event was triggered
619Yes
ctrlKeyReturns whether or not the "CTRL" key
was pressed when an event was triggered
619Yes
metaKeyReturns whether or not the "meta" key
was pressed when an event was triggered
619Yes
relatedTargetReturns the element related to the
element that triggered the event
No19Yes
screenXReturns the horizontal coordinate of the
mouse pointer when an event was triggered
619Yes
screenYReturns the vertical coordinate of the mouse
pointer when an event was triggered
619Yes
shiftKeyReturns whether or not the "SHIFT" key was
pressed when an event was triggered
619Yes

Other Event Attributes:

PropertyDescriptionIEFOW3C
bubblesReturns a Boolean value that indicates
whether or not an event is a bubbling event
No19Yes
cancellableReturns a Boolean value that indicates
whether or not an event can have
its default action prevented
No19Yes
currentTargetReturns the element whose event
listeners triggered the event
No19Yes
Returns the element that triggered the eventNo19Yes
timeStampReturns the time stamp, in milliseconds
from the epoch (system start or event trigger)
No19Yes

Standard event handlers

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

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.

addEventListener

This method adds an event handler to an element for an event type without dropping existing handlers.

Links:

removeEventListener

This methods removes a particular event handler from an element, given event type.

Links:

keyCode

keyCode property of a keyboard event contains a number indicating which key was pressed.

For keydown event, key codes include 65 for A through 90 for Z, and 48 for 0 through 57 for 9.

Examples:

document.addEventListener("keydown", function(evt) {
  alert("Key pressed; key code: " + evt.keyCode);
  evt.preventDefault();
});

Links:

Further reading

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.