CIM 322 Topic 4 Event Driven JS
CIM 322 Topic 4 Event Driven JS
2
JavaScript Events
• Event - change in the state of an object.
• In HTML, events can be fired/triggered by
actions of a user or the browser.
• JavaScript listens (monitors) to these events
using Event Listeners.
• JS can react to these events when they occur
by allowing some specified code to be
executed.
3
• This process of reacting to the events is called
Event Handling.
• JavaScript handles the HTML events via Event
Handlers.
• Event handlers are essentially function
declarations.
4
Types of Events
1. Mouse events: events fired by mouse
actions.
2. Keyboard events: occur every time the
user presses or depresses a key.
3. Progression events: These are more
generic events that occur at different
stages of an object e.g. when the
document loads.
5
4. Form events: These occur when
something in the form changes.
5. Mutation events: These occur when
DOM nodes are modified.
6. Touch events: These occur when the
user touches the sensor.
7. Error events: These occur when an error
occurs.
6
Common HTML Event Listeners
1. onblur - An element, such as a radio button,
becomes inactive
Tigger: clicking away from the element
2. onfocus - An element, such as a command
button, becomes active
Trigger: clicking away from the element
3. onchange - An HTML element e.g. text field
value, has been changed
Tigger: keyboard
7
4. onclick - The user clicks an HTML element
Trigger: Key Press, Mouse one click, one touch
screen
5. onmouseover - The user moves the mouse over
an HTML element
Trigger: mouse pointer moves over, long touch
screen
6. onmouseout - The user moves the mouse away
from an HTML element
Trigger: mouse, touch screen
8
7.onkeydown - The user pushes a keyboard key
Trigger: key press
8. Onkeyup – user releases a key
9. Onload - The browser has finished loading the
page
Trigger: web page finishes opening
10. onsubmit – a user submits a form
Tigger : click submit button
9
Associating HTML Elements with
Events
10
Connecting an Event Listener to
an Event Handler
• You can connect your code (event handler) to
an event listener in three ways:
i. Using HTML attributes
ii. Using the getElementById() method
iii. Using the addEventListener() method
11
Handling Events Using HTML
Attributes
• Example:
<input type="button" value="Say Hello"
onclick="sayHello()" />
12
• Example App: App Captures Scores using a Form and Calculates
Average upon button click
<!DOCTYPE html>
<head><title>Attribute Event Listener</title></head>
<body>
<h2 align="center">Attribute Event Listener Demo</h2>
<form>
ENG:<input type="text" id="eng" value=""><br /><br /> MATH:<input
type="text" id="math" value=""><br /><br />
Average:<input type="text" id="average" value="" disabled><br /><br
/>
<input type="button" id=“but Calc" value="Calculate"
onclick="calculator()" />
<input type="reset" name="butReset" value="Reset" /><br /><br />
</form>
13
<script>
function calculator(){
var engMark = parseInt(document.getElementById("eng").value);
var mathMark = parseInt(document.getElementById("math").value);
var avgMark = (engMark + mathMark)/2; avgMark =
avgMark.toFixed(2);
document.getElementById("average").value = avgMark; //Output
}
</script>
</body>
</html>
14
Using an Event Object to Connect
Event Listener with Event handler
• It’s a 2 step process
Step 1: Identifying the element that fired the
event
• The getElementById() method of the
Document object is used.
• It identifies the element by its id attribute.
15
• Example:
• Var myButton =
document.getElementById(“butCalc");
• The method returns the element as an object.
• This allows for retrieval of information about
the element or the ability to change the
values assigned to its attributes.
• Note: no parentheses are added after the
function name.
16
Step 2: Connecting the element object to an
event handler (a function)
Example:
myButton.onclick = calculator ;
listener
Element object handler
• This effectively binds the element, event
listener and the event handler together.
17
• Example App:
<!DOCTYPE html>
<head><title>Object Event Listener</title></head>
<body>
<h2 align="center">Object Event Listener Demo</h2>
<form>
ENG:<input type="text" id="eng" value=""><br /><br />
MATH:<input type="text" id="math" value=""><br /><br />
Average:<input type="text" id="average" value="" disabled><br /><br
/>
<input type="button" id="butCalc" value="Calculate" />
<input type="reset" id="butReset" value="Reset" /><br /><br />
</form>
18
<script>
var myButton = document.getElementById("butCalc");
myButton.onclick = calculator;
function calculator(){
var engMark =
parseInt(document.getElementById("eng").value);
var mathMark =
parseInt(document.getElementById("math").value);
var avgMark = (engMark + mathMark)/2;
avgMark = avgMark.toFixed(2);
document.getElementById("average").value = avgMark;
//Output
}
</script>
</body>
</html>
19
Handling Events Using the
addEventListener() Method
• Its most standard way of connecting an event
listener and handler.
• The addEventListener() method attaches an
event handler to a specified element.
• Syntax:
element.addEventListener(event, function);
20
Parameters:
i). event – specifies the type of the event
e.g."click“, "mousedown“.
ii). function - event handler.
21
• Example:
var btn1=document.getElementById("myBtn");
btn1.addEventListener("click", myFunction);
Alt:
document.getElementById("myBtn").addEventLi
stener("click", myFunction);
• Note: the "on" prefix is not used e.g. use
"click" instead of "onclick".
22
• Example:
<!DOCTYPE html>
<head><title>Add Event Listener Method</title></head>
<body>
<h2 align="center">Add Event Listener Method Demo</h2>
<form>
ENG:<input type="text" id="eng" value=""><br /><br />
MATH:<input type="text" id="math" value=""><br /><br />
Average:<input type="text" id="average" value=""
disabled><br /><br />
<input type="button" id="butCalc" value="Calculate" />
<input type="reset" id="butReset" value="Reset" /><br
/><br />
</form>
23
<script>
var butCalculate = document.getElementById("butCalc");
butCalculate.addEventListener("click", calculator);
function calculator(){
var engMark = parseInt(document.getElementById("eng").value);
var mathMark = parseInt(document.getElementById("math").value);
var avgMark = (engMark + mathMark)/2;
avgMark = avgMark.toFixed(2);
document.getElementById("average").value = avgMark;
}
</script>
</body>
</html>
24
Adding More Than One Event
Handlers to addEventListener()
• The addEventListener() method allows you to
add multiple events to the same element,
without overwriting existing ones.
• Example:
<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", myFunction2);
</script>
25
Example: App clears the ENG and MATH fields when the user clicks in
the AVERAGE field.
<!DOCTYPE html>
<head>
<title>Object Event Listener</title>
</head>
<body>
<h2 align="center">Object Event Listener Demo</h2>
<form>
ENG:<input type="text" id="txteng" value=""><br /><br />
MATH:<input type="text" id="txtmath" value=""><br /><br />
Average:<input type="text" id="txtavg" value="" ><br /><br />
<input type="button" id="butcalc" value="Calculate" />
<input type="reset" id="butReset" value="Reset" /><br /><br />
</form>
26
<script>
var txtAvg = document.getElementById("txtavg");
txtAvg.addEventListener("click", clearTxtEng, false);
txtAvg.addEventListener("click", clearTxtMath);
function clearTxtEng(){
document.getElementById('txteng').value = '';
}
function clearTxtMath(){
document.getElementById('txtmath').value = '';
}
</script>
</body>
</html>
27
Handling Two Different Events
• It can also take events of different types.
• Example: App computes average mark upon
click of Calculate Button and displays remarks
alert when the user moves the mouse away
from the button.
28
• Example Web Page:
<!DOCTYPE html>
<head>
<title>Object Event Listener</title>
</head>
<body>
<h2 align="center">Object Event Listener Demo</h2>
<form>
ENG:<input type="text" id="eng" value=""><br /><br />
MATH:<input type="text" id="math" value=""><br /><br />
Average:<input type="text" id="average" value="" disabled><br /><br
/>
<input type="button" id="butcalc" value="Calculate" />
<input type="reset" id="butReset" value="Reset" /><br /><br />
</form>
29
<script>
var avgMark = 0;
var butCalc = document.getElementById("butcalc");
butCalc.addEventListener("click", calculator);
butCalc.addEventListener("mouseout", remarks);
function calculator(){
var engMark = parseInt(document.getElementById("eng").value);
var mathMark = parseInt(document.getElementById("math").value);
avgMark = (engMark + mathMark)/2;
avgMark = avgMark.toFixed(2);
document.getElementById("average").value = avgMark;
}
function remarks(){
var remark = (avgMark >= 40)? "Pass" : "Fail";
alert("Remark:" + remark);
}
</script>
</body>
</html>
30
Removing an Event Listener from an
Element
• The removeEventListener() method removes
an event handler from an element registered
using the addEventListener() method.
• Example
element.removeEventListener("mousemove",
myFunction);
• Example App : This App removes the alert
after displaying the message.
31
<!DOCTYPE html>
<head>
<title>Remove Event Listener</title></head>
<body>
<h2 align="center">Remove Event Listener Demo</h2>
<form>
ENG:<input type="text" id="eng" value=""><br /><br />
MATH:<input type="text" id="math" value=""><br /><br />
Average:<input type="text" id="average" value=""
disabled><br /><br />
<input type="button" id="butcalc" value="Calculate" />
<input type="reset" id="butReset" value="Reset" /><br
/><br />
</form>
32
<script>
var avgMark = 0;
var butCalc = document.getElementById("butcalc");
butCalc.addEventListener("click", calculator);
butCalc.addEventListener("mouseout", remarks);
function calculator(){
var engMark = parseInt(document.getElementById("eng").value);
var mathMark = parseInt(document.getElementById("math").value);
avgMark = (engMark + mathMark)/2;
avgMark = avgMark.toFixed(2);
document.getElementById("average").value = avgMark;
}
function remarks(){
var remark = (avgMark >= 40)? "Pass" : "Fail";
alert("Remark:" + remark);
butCalc.removeEventListener("mouseout", remarks);
}
</script>
</body>
</html>
33
Some Common Element Events
1. The onfocus event
• The onfocus event occurs when an element
gets focus.
• The onfocus event is most often used with
<input>, <select>, and <a>.
Example App: the App sets text field red upon
receiving focus
34
<!DOCTYPE html>
<html>
<head><title>OnFocus Event</title></head>
<body>
<h2>onfocus Event Demo</h2>
<form>
First Name: <input type="text" id="fname" />
</form>
<script>
var txtFName = document.getElementById("fname");
txtFName.addEventListener("focus", changeBgColor);
function changeBgColor() {
txtFName.style.backgroundColor = "red";
}
</script>
</body>
</html>
35
2. The onblur event
• The onblur event occurs when an object loses
focus.
• The onblur event is most often used with form
validation code (e.g. when the user leaves a
form field).
• Example: App sets text field red it gets focus
and back to white when it looses focus
36
<!DOCTYPE html>
<html>
<head><title>OnBlur Event</title></head>
<body>
<h2>onblur Event Demo</h2>
<form>
First Name: <input type="text" id="fname" /><br /><br />
First Name: <input type="text" id="fname" />
</form>
<script>
var txtFName = document.getElementById("fname");
txtFName.addEventListener("focus", changeBgColor);
txtFName.addEventListener("blur", resetBgColor);
function changeBgColor() {
txtFName.style.backgroundColor = "red";
}
function resetBgColor() {
txtFName.style.backgroundColor = "";
}
</script>
</body>
</html>
37
3. Onchange Event
• The onchange event occurs when the value of
an element has been changed.
• It occurs when the element loses focus after
the content has been changed.
• Example: App changes content to upper case
when the content changes
38
<!DOCTYPE html>
<html>
<head<title>On Change Event</title>
<body>
<h2>On Change Event Demo</h2>
Name: <input type="text" id="fname">
<script>
var txtFName = document.getElementById("fname")
txtFName.addEventListener("change", changeToUppercase);
function changeToUppercase() {
var entry = document.getElementById("fname");
entry.value = entry.value.toUpperCase();
}
</script>
</body>
</html>
39
Scripting Textarea
• Textarea: is an object that provides multiple lines entry.
• Example:
• <textarea name="comment" id="comment" rows="S"
cols="40"></textarea>
• The name and id attributes of these controls should be
set to the same value.
• The value property is used to get the value string,.
• The length property of the String object to get the
number of characters in the string.
40
• Setting the value property of a Textarea object
replaces the text contents.
• Example: set object content
document.getElementById(“txtacomment”).valu
e = “Hello”;
• Example: read object content
var comments =
document.getElementById(“txtacomment”).valu
e;
41
if (comment.length == 0) {
alert("Please enter a comment.");
}
• When the user presses the Enter key while
typing in a text area, a hard return is entered
into the text. Hard returns appear as
characters in the value property.
42
• When the user types past the end of a line in a
text area and a new line is automatically
started, a soft return occurs. Soft returns do
not appear as characters in the value property.
43
Using the checked Property to Handle
Check Boxes/Radio Buttons Events
• The checked property sets or returns the
checked state of a radio button/check box.
• It returns values true or false.
• true - The radio button/check box is checked.
• false – (Default) The radio button/check box is
not checked.
44
Checking the checked Status
Syntax:
var variableName = radioObject.checked
• Example:
var x = document.getElementById("myRadio");
Status = x.checked;
45
Setting the checked Property
• Syntax:
radioObject.checked = true|false;
• Example:
var x = document.getElementById("myRadio");
x.checked = true;
46
• Example App: App changes the case of the
entry upon checking a radio button
47
<!DOCTYPE html>
<html>
<head><title>Radio Button Events</title></head>
<body>
<h2>Radio Buttons Events Demo</h2>
<p>App changes case of the name</p>
<form>
<input type="radio" id="ucase“ name="cases" value=""
/>Uppercase<br /><br />
<input type="radio" id="lcase“ name="cases" value=""
/>Lowercase<br /><br />
First Name: <input type="text" id="name"
value="Donald">
</form>
48
<script>
var radUpperCase = document.getElementById("ucase");
radUpperCase.addEventListener("click", changeCase);
var radLowerCase = document.getElementById("lcase");
radLowerCase.addEventListener("click", changeCase);
function changeCase() {
var status = radUpperCase.checked;
var entry = (status)?
document.getElementById("name").value.toUpperCase():
document.getElementById("name").value.toLowerCase();
document.getElementById("name").value = entry;
}
</script>
</body>
</html>
49