CSE 190M Web Programming

Lecture 20: Events

Reading: Chapter 11

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, Victoria Kirst and Roy McElmurry IV. 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.

Valid HTML5 Valid CSS

11.1: Event-Handling

JavaScript events

abort blur change click dblclick error focus
keydown keypress keyup load mousedown mousemove mouseout
mouseover mouseup reset resize select submit unload

Attaching event handlers the jQuery way

element.onevent = function;
element.event(function);
// call the playNewGame function when the Play button is clicked
$("#play").click(playNewGame);

function playNewGame(evt) {
	// respond to the click event
}

Attaching many event handlers

You often need to attach an event handler to a group of elements.

Exercise: hover bounce

We will elaborate on the bounce.html example.

  • Add code so that when we mouseover an img it's src changes to dai_gurren.jpg
  • If we mouse over the #square element, change it's background-color instead.

Custom DOM events

Custom jQuery events

The jQuery event object

function handler(event) {
	// an event handler function ...
}
method / property name description
type what kind of event, such as "click" or "mousedown"
target the element on which the event handler was registered
preventDefault() prevents browser from performing its usual action in response to the event
stopPropagation() prevents the event from bubbling up further
stopImmediatePropagation() prevents the event from bubbling and prevents any other handlers from being executed

Specific events

jQuery supports and standardizes all of these, though some events do not have dedicated event functions

Mouse events

clicking
click user presses/releases mouse button on the element
dblclick user presses/releases mouse button twice on the element
mousedown user presses down mouse button on the element
mouseup user releases mouse button on the element
movement
mouseover mouse cursor enters the element's box
mouseout mouse cursor exits the element's box
mousemove mouse cursor moves around within the element's box

Mouse event objects

The event passed to a mouse handler has these properties:

mouse event
property/method description
clientX, clientY coordinates in browser window
screenX, screenY coordinates in screen
offsetX, offsetY coordinates in element (non-standard)
pageX, pageY coordinates in entire web page
which which mouse button was clicked

Mouse event example

<pre id="target">Move the mouse over me!</pre>
window.onload = function() {
	$("#target").mouseover(showCoords);
};

function showCoords(event) {
	$("#target").html(
		  "page   : (" + event.pageX + ", " + event.pageY + ")\n"
		+ "screen : (" + event.screenX + ", " + event.screenY + ")\n"
		+ "client : (" + event.clientX + ", " + event.clientY + ")"
	);
}
Move the mouse over me!

The keyword this

this.fieldName                  // access field
this.fieldName = value;          // modify field

this.methodName(parameters);    // call method

Event handler binding

window.onload = function() {
	$("textbox").observe("mouseout", booyah);   // bound to text box here
	$("submit").observe("click", booyah);       // bound to submit button here
};

function booyah() {           // booyah knows what object it was called on
	this.value = "booyah";
}

Fixing redundant code with this

<fieldset>
	<label><input type="radio" name="ducks" value="Huey"  /> Huey</label>
	<label><input type="radio" name="ducks" value="Dewey" /> Dewey</label>
	<label><input type="radio" name="ducks" value="Louie" /> Louie</label>
</fieldset>
$(":radio").click(processDucks);
function processDucks() {
	if ($("huey").checked) {
		alert("Huey is checked!");
	} else if ($("dewey").checked) {
		alert("Dewey is checked!");
	} else {
		alert("Louie is checked!");
	}
	alert(this.value + " is checked!");
}

Page/window events

namedescription
load, unload the browser loads/exits the page
resize the browser window is resized
error an error occurs when loading a document or an image
contextmenu the user right-clicks to pop up a context menu
$(window).on('contextmenu', function);

Keyboard/text events

name description
keydown user presses a key while this element has keyboard focus
keyup user releases a key while this element has keyboard focus
keypress user presses and releases a key while this element has keyboard focus
focus this element gains keyboard focus
blur this element loses keyboard focus
select this element's text is selected or deselected)

Key event objects

property name description
which ASCII integer value of key that was pressed
(convert to char with String.fromCharCode)
altKey, ctrlKey, shiftKey true if Alt/Ctrl/Shift key is being held

Form events

event name description
submit form is being submitted
reset form is being reset
change the text or state of a form control has changed

Stopping an event's browser behavior

<form id="exampleform" action="http://foo.com/foo.php">...</form>
$(function() {
	$("#exampleform").submit(checkData);
});

function checkData(event) {
	if ($("#city").val() == "" || $("#state").val().length != 2) {
		alert("Error, invalid city/state.");  // show error message
		event.preventDefault();
	}
}

Which element gets the event

<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
</body>
$(function() {
	$("body, div, p, em").click(hello);
});

function hello() {
	alert("You clicked on the " + $(this).attr("tag"));
}

What happens when I click on the span? Which element will get the event?

Answer: All of them!

Event bubbling

event flow
<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
</body>

Bubbling example

<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
</body>
$(function() {
	$("body, div, p, em").click(hello);
});

function hello() {
	alert("You clicked on the " + this.nodeName);
}

Runnable example

Stopping an event from bubbling

Use the stopPropagation() method of the jQuery event to stop it form bubbling up.

<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
</body>
$(function() {
	$("body, div, p, em").click(hello);
});

function hello(evt) {
	alert("You clicked on the " + this.nodeName);
	evt.stopPropagation();
}

Runnable example

Multiple handlers

<body>
	<div>
		<p>
			Events are <em>crazy</em>!
		</p>
	</div>
	<p>Another paragraph!</p>
</body>
$(function() {
	$("body, div, p, em").click(hello);
	$("div > p").click(anotherHandler);
});

function hello() {
	alert("You clicked on the " + this.nodeName);
}
function anotherHandler() {
	alert("You clicked on the inner P tag");
}

What happens when the first p tag is clicked? Runnable example

Stopping an event right now

function anotherHandler(evt) {
	alert("You clicked on the inner P tag");
	evt.stopImmediatePropagation();
}

Runnable example

stopImmediatePropogation() example

$("div a").click(function() {
   // Do something
});

$("div a").click(function(evt) {
   // Do something else
   evt.stopImmediatePropagation();
});

$("div a").click(function() {
   // THIS NEVER FIRES
});

$("div").click(function() {
   // THIS NEVER FIRES
});

jQuery handler return value

<form id="exampleform">
	...
	<button>Done</button>
</form>
$(function() {
	$("#exampleform").submit(cleanUpData);
	$("button").click(checkData);
});

function checkData() {
	if ($("#city").val() == "" || $("#state").val().length != 2) {
		alert("Error, invalid city/state.");  // show error message
		return false;
	}
}