- Event types:
- Mouse-related: mouse movement, enter/leave element, button click
- Keyboard-related: down, up, press
- Focus-related: focus in, focus out (blur)
- Timer events
- Miscellaneous:
- Content of an element has changed.
- Page loaded/unloaded.
- Uncaught error.
- Creating an event handler: must specify 3 things:
- The event of interest.
- An element of interest.
- Javascript to invoke when the event occurs on the element.
- Option #1: in the HTML:
<div onclick="mouseClick('id42');">...</div>
- Option #2: from Javascript using the DOM:
element.onclick = mouseClick;
Can't pass arguments directly with this method, but can fudge it:
element.onclick = function() {mouseClick("id42");};
- Event handlers typically need information about the event, such as
mouse position or the specific key/button that was pressed.
- Interesting information in the event:
- button: mouse button that was pressed
- keyCode: identifier for the keyboard key that was pressed (not
necessarily an ASCII character!)
- charCode: integer Unicode value corresponding to key,
if there is one.
- clientX, clientY: mouse position relative to the
document in the browser window
- screenX, screenY: mouse position in screen coordinates
- This information is available in an event object passed to the handler:
in Firefox the event is normally passed as the first argument to the
handler:
- IE uses a global variable event to hold the current event
- Example: dragExample.html:
<body>
<div id="div1" onmousedown="mouseDown(event);"
onmousemove="mouseMove(event);"
onmouseup="mouseUp(event);">Drag Me!</div>
<script type="text/javascript">
//<![CDATA[
isMouseDown = false;
function mouseDown(event) {
prevX = event.clientX;
prevY = event.clientY;
isMouseDown = true;
}
function mouseMove(event) {
if (!isMouseDown) {
return;
}
element = document.getElementById("div1");
element.style.left = (element.offsetLeft +
(event.clientX - prevX)) + "px";
element.style.top = (element.offsetTop +
(event.clientY - prevY)) + "px";
prevX = event.clientX;
prevY = event.clientY;
}
function mouseUp(event) {
isMouseDown = false;
}
//]]>
</script>
</body>
- Event-based programming is different from traditional imperative
programming:
- Must wait for someone to invoke your code.
- Key is to maintain control through events: make sure you have
declared enough handlers; last resort is a timer.
- Typically an event handler works by first figuring out what has
changed (e.g., mouse coordinates in dragging example), then
responding to that.