07 Events
07 Events
Javascript Events
CSE 190 M (Web Programming), Spring 2007
University of Washington
Lecture summary
in these slides, we'll see how to respond to several events
Javascript event code seen previously was obtrusive (in the HTML)
this is bad style (mixes content and behavior)
this week we'll see how to write unobtrusive Javascript code
HTML with minimal Javascript inside
uses the DOM to attach and execute all Javascript functions
one drawback: significant browser compatibilities
Click me
this is considered bad style in modern web programming (HTML is cluttered with Javascript calls)
Click me
function initializeBody() {
var name = document.getElementById("ok");
name.event = function;
...
}
to set up an event handler, get the element's DOM object and set the appropriate event property to the
function to call (no parentheses)
Mouse events
DOM objects for HTML elements have the following properties:
clicking
onmousedown : user presses down mouse button on this element
onmouseup : user releases mouse button on this element
onclick : user presses/releases mouse button on this element
ondblclick : user presses/releases mouse button twice on this element
movement
onmouseover : mouse cursor enters this element's box
onmouseout : mouse cursor exits this element's box
onmousemove : mouse cursor moves within this element's box
myElement.onmousemove = myFunction;
function initializeBody() {
document.getElementById("dare").onmousedown = colorIt;
}
function colorIt() {
this.style.backgroundColor = "red";
}
in event handler, element can refer to itself using keyword this (don't have to call
document.getElementById again)
function initializeBody() {
var dareDiv = document.getElementById("dare");
dareDiv.onmousedown = colorIt;
dareDiv.onmouseup = uncolorIt;
}
function colorIt() {
this.style.backgroundColor = "red";
}
function uncolorIt() {
this.style.backgroundColor = "transparent";
}
Event nesting
<div id="gum"><img src="gum.png" alt="gum" />
Double your pleasure, <em>double your fun</em>!</div>
function initializeBody() {
document.getElementById("gum").ondblclick = doBorder;
}
function doBorder(event) {
event = standardizeEvent(event);
event.srcElement.style.border = "2px dashed blue";
}
Keyboard events
DOM objects for HTML elements have the following properties:
onkeydown : user presses a key while this element has keyboard focus
onkeyup : user releases a key while this element has keyboard focus
onkeypress : user presses and releases a key while this element has keyboard focus
onfocus : this element gains keyboard focus
onblur : this element loses keyboard focus
// script 2
window.onload = init2;
Using addEventListener
// script 1
window.addEventListener("load", init1, false);
// script 2
window.addEventListener("load", init2, false);
Browser/page events
onload : the browser loads the page
onunload : the browser exits the page
onresize : the browser window is resized
onerror : an error occurs when loading a document or an image