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:
- Via an element attribute directly in HTML: <body onload="alert('Hello World!');">
- Via JavaScript, by assigning the event type to an element attribute: document.onclick = clickHandler;
- 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:
- Interactive event handlers - depend on user interaction with the HTML page; ex. clicking a button
- 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.
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
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:
- EventTarget.addEventListener(), developer.mozilla.org
- JavaScript HTML DOM EventListener, w3schools.com
- HTML DOM Events, w3schools.com
removeEventListener
This methods removes a particular event handler from an element, given event type.
Links:
- EventTarget.removeEventListener(), developer.mozilla.org
- JavaScript HTML DOM EventListener, w3schools.com
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:
- KeyboardEvent.keyCode, developer.mozilla.org
- KeyboardEvent keyCode Property, w3schools.com
Further reading
- Event reference, developer.mozilla.org
- DOM on-event handlers, developer.mozilla.org
- JavaScript Events, w3schools.com
- HTML DOM Events, w3schools.com