Handling events
Objectives
- use event handlers to work with windows
- capture mouse movements and clicks
- use form event handling to process forms
- capture and react to keyboard events
Important note
One thing you will notice throughout these notes is that a lot depends
upon differences between browsers - especially when dealing with the
screen and the keyboard. This greatly complicates programming. Fortunately,
the same Ajax libraries that make working with asynchronous Javascript
server requests easier also provide libraries that often make event
handling more standardized between browsers. If you need to work with
the screen or keyboard, you would be best off investigating the current
Ajax libraries.
Overview of events
- Return false from an event handler to prevent the browser from executing
its default response after your handler has finished execution.
- The old style of setting event handlers inline in HTML tags is discouraged.
- The traditional style of setting object event handler properties is common,
but suffers from not being easy to attach multiple handlers to a single
event.
- The new style for adding event handlers allows for fine tuning of the events you want to handle and when you want to handle them.
- The new style for adding event handlers can be applied to more than just HTML elements.
- The new style for adding an event handler is: element.addEventListener(event, function, useCapture)
- element: the element that would receive the event notification
- event: the event you want to handle
- function: the handler for the event
- useCapture: default is false, refers to when event is seen
- The new style for removing an event handler is: element.removeEventListener(event, function, useCapture)
- Internet Explorer prior to IE9 use attachEvent and detachEvent for the new style.
- It is difficult to guarantee compatability across all browsers at this point with the
new style, but polyfills are available for most of the functionality.
- Note that the properties that contain event handlers start with "on", but the events
themselves do not have the "on" prefix.
Window events
- Due to restrictions on what JavaScript is allowed to do in some browsers,
some of these window event handlers may not be very useful now.
- onload: fires when the document is done loading
- onresize: when the window changes size
- onmove: when the window moves
- onfocus: when the window becomes the active window
- onblur: when the window loses focus
- oncontextmenu: when the mouse is right clicked
- onscroll: sometimes used to zoom in and out
- Previous examples have used the window onload handler. It is useful to be able to
place new onload handlers into a queue with existing onload event handlers.
The example at event01.html
demonstrates how multiple onload event handlers can be set.
<!DOCTYPE html>
<html>
<head>
<title>Multiple onload handlers</title>
<script>
var ctr = 0;
addInit(func1);
addInit(func2);
addInit(func3);
addInit(func4);
addInit(func5);
function addInit(func) {
var onloadFunc = window.onload;
if (typeof onloadFunc == "function") {
window.onload = function() {
if (onloadFunc) {
onloadFunc();
}
func();
}
} else {
window.onload = arguments[0];
}
}
function func1() {
document.getElementById('content').style.backgroundColor = "#FFFF00";
}
function func2() {
document.getElementById('content').style.color = "#FF0000";
}
function func3() {
document.getElementById('content').style.fontSize = "24pt";
}
function func4() {
document.getElementById('content').style.fontWeight = "bold";
}
function func5() {
document.getElementById('content').style.textAlign = "center";
}
</script>
</head>
<body>
<div id="content">Hello, world!</div>
</body>
</html>
Mouse events
- onmousedown: when a mouse button is pressed
- onmouseup: when a mouse button is released
- onmousemove: when the mouse moves
- onmouseover: when the mouse moves over an element
- onmouseout: when the mouse moves off an element
- onclick: when the mouse is left-clicked once on an element
- oncontextmenu: when the mouse is right-clicked once on an element
- ondblclick: when the mouse is clicked twice quickly on an element
- See event03.html for a sample of using
document.onmousedown to disable context menus.
<!DOCTYPE html>
<html>
<head>
<title>Disable context menu</title>
<script>
if (typeof document.oncontextmenu == "object") {
if (document.all) document.onmousedown = captureMouseDown; // IE
else document.oncontextmenu = captureMouseDown; // Safari
} else {
window.oncontextmenu = captureMouseDown; // FF
}
function captureMouseDown(evt) {
var mouseClick;
if (evt) mouseClick = evt.which;
else mouseClick = window.event.button;
if (mouseClick >= 1 && mouseClick <=3) {
alert('Context menu disabled');
return false;
}
}
</script>
</head>
<body>
<div id="content">Try to right click in this window.</div>
</body>
</html>
- See event04.html for a sample
of handling mouse movement events.
<!DOCTYPE html>
<html>
<head>
<title>Detect mouse movement</title>
<script>
document.onmousemove = moveHandler;
function moveHandler(evt) {
if (!evt) evt = window.event;
document.getElementById('content').innerHTML = 'The mouse is at ' + evt.clientX + ', ' + evt.clientY;
}
</script>
</head>
<body>
<div>Move the mouse.</div>
<div id="content"></div>
</body>
</html>
Form events
- onsubmit: when the submit button is clicked; return false to abort form submission
- onreset: when the reset button is clicked
- onblur: when the form element loses focus
- onfocus: when the form element becomes the active element
- onselect: when text is selected
- onclick: when an element (usually a checkbox, radio button, or button) is clicked
- onchange: when a form element is changed
- oncopy: when content in an element is copied (see oncopy.html)
<html>
<head>
<title>Preventing copying</title>
<script>
window.onload = function() {
document.getElementById('content').oncopy =
function() { alert('No copying allowed'); return false; };
}
</script>
</head>
<body>
<h1>Preventing copying</h1>
<div id="content">You can't copy this if JavaScript is working properly.</div>
</body>
</html>
- oncut: when content in an element is cut
- onpaste: when content in an element is pasted
- See event05.html
for an example of using some form events.
<!DOCTYPE html>
<html>
<head>
<title>Detect form events</title>
<script>
function handleChange(e) { alert("The text has changed: " + e.value); }
function handleClick(e) { alert("Stop clicking me - it tickles."); }
function handleFocus(e) { alert("Welcome to the best element on the page"); }
function handleBlur(e) { alert("Please don't leave so soon."); }
function handleSubmit(e) { alert("Sorry, I can't submit the form Dave."); return false; }
function handleReset(e) { alert("Good idea. Too bad I'm not going to do it."); return false; }
</script>
</head>
<body>
<div>Do stuff to the form.<br /><br /></div>
<div>
<form method="GET" action="http://www.google.com/"
onsubmit="return handleSubmit(this);" onreset="return handleReset(this);" >
Change some text and move along:
<input type="text" size="30" onchange="handleChange(this);" /><br><br>
Touchy element:
<input type="checkbox" onclick="handleClick(this);" /><br><br>
Best element:
<input type="checkbox" onclick="handleFocus(this);" /><br><br>
Lonely element:
<input type="text" onblur="handleBlur(this);" /><br><br>
<input type="submit" />
<input type="reset" />
</form>
</div>
</body>
</html>
Key events
- onkeydown: when a key has been pressed
- onkeyup: when a key has been released
- onkeypress: when a key has been pressed and then released
- See event06.html
for an example of using some key event handlers.
<!DOCTYPE html>
<html>
<head>
<title>Detect key events</title>
<script>
document.onkeydown = handleDown;
document.onkeyup = handleUp;
document.onkeypress = handlePress;
function handlePress(evt) {
var thiskey = evt ? evt.which : window.event.keyCode;
var e = document.getElementById('content');
e.innerHTML = e.innerHTML + "<br>Key pressed: " + thiskey;
}
function handleUp(evt) {
var thiskey = evt ? evt.which : window.event.keyCode;
var e = document.getElementById('content');
e.innerHTML = e.innerHTML + "<br>Key up: " + thiskey;
}
function handleDown(evt) {
var thiskey = evt ? evt.which : window.event.keyCode;
var e = document.getElementById('content');
e.innerHTML = e.innerHTML + "<br>Key down: " + thiskey;
}
</script>
</head>
<body>
<div>Press keys.<br><br></div>
<div id="content"></div>
</body>
</html>