Except where otherwise noted, the contents of this document are
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst.
All rights reserved.
Any redistribution, reproduction, transmission, or storage of part
or all of the contents in any form is prohibited without the author's
expressed written permission.
Event-Handling
11.1: Event-Handling
11.2: Case Study: Multiplication Quiz
JavaScript events
abort
blur
change
click
dblclick
error
focus
keydown
keypress
keyup
load
mousedown
mousemove
mouseout
mouseover
mouseup
reset
resize
select
submit
unload
the click event (onclick) is just one of many events that can be handled
The keyword this
this.fieldName// access field
this.fieldName = value; // modify field
this.methodName(parameters); // call method
all JavaScript code actually runs inside of an object
by default, code runs in the global window object (so this === window)
all global variables and functions you declare become part of window
the this keyword refers to the current object
Event handler binding
window.onload = function() {
document.getElementById("textbox").onmouseout = booyah;
document.getElementById("submit").onclick = booyah; // bound to submit button here
};
function booyah() { // booyah knows what object it was called onthis.value = "booyah";
}
event handlers attached unobtrusively are bound to the element
function processDucks() {
if (document.getElementById("huey").checked) {
alert("Huey is checked!");
} else if (document.getElementById("dewey").checked) {
alert("Dewey is checked!");
} else {
alert("Louie is checked!");
}alert(this.value + " is checked!");
}
if the same function is assigned to multiple elements, each gets its own bound copy
The event object
function name(event) {
// an event handler function ...
}
Event handlers can accept an optional parameter to represent the event that is occurring. Event objects have the following properties / methods:
property name
description
type
what kind of event, such as "click" or "mousedown"
stops the browser from doing its normal action on an event; for example, stops the browser from following a link when <a> tag is clicked, or stops browser from submitting a form when submit button is clicked
stopPropagation
stops the browser from showing this event to any other objects that may be listening for it
you can also return false; from your event handler to stop an event
it is considered bad form to directly assign to window.onload
multiple .js files could be linked to the same page, and if they all need to run code when the page loads, their window.onload statements will override each other
by calling window.addEventListener instead, all of them can run their code when the page is loaded