Event-Driven Programs
Our programs can react to events on the client side by writing event handlers.
There is an example of creating noughts and crosses starting from slide 13 of the lecture. This is hosted live at: https://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/jsBoard.html.
Events
Event handlers are associated with HTML elements for a specific event. We can do this with attributes:
<input type="button" value="Help" onclick="Help()">
or by using a JavaScript function:
// For Browsers
window.addEventListener("load", Hello)
// Internet Explorer
window.attachEvent("onload", Hello)
Attaching Event Handlers
We can use JavaScript to add a handler to a HTML element. The following conditional statement also supports IE:
// adding
if (window.addEventListener) {
window.addEventListener("load", Hello)
} else {
window.attachEvent("onload", Hello)
}
// removing
if (window.removeEventListener) {
window.removeEventListener("load", Hello)
} else {
window.dettachEvent("onload", Hello)
}
This is required as IE has different function names for adding events.
We can also place an event attribute on the element like so:
<html>
<head>
</head>
<body onload="Hello()">
</body>
</html>
We typically use onload
with the body
element or window
object.
Other Events
Event | Description | Attribute |
---|---|---|
focus | Occurs when a form field receives input. | onFocus |
change | Occurs when an input is modified. | onChange |
blur | Occurs when an HTML element loses focus. | onBlur |
click | Occurs when an object is clicked. | onClick |
keydown | Occurs when a users presses a key. | onkeydown |
mouseOver | Occurs once each time the mouse pointer moves over an HTML element. | onMouseOver |
select | Occurs when a users selects some of the text within an object. | onSelect |
submit | Occurs when a user submits a form. | onSubmit |
Creating Custom Events
When an event occurs, an event object, with methods and attributes, is created. We can make our own event objects which will be passed to event handler functions (not in IE).
In Internet Explorer we can access only the most recent event with window.event
.
<html>
<body onKeyDown="processKey(event)">
<script>
function processKey(e) {
e = e || window.event // this accommodates for IE
document.getElementById("key").innerHTML = String.fromCharCode(e.keyCode) + 'has been pressed '
}
</script>
<!-- key code will appear in the paragraph below -->
<p id="key"></p>
</body>
</html>