0% found this document useful (0 votes)
11 views

LU02 Web Tecnologies - JavaScript (Updated 180422)

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

LU02 Web Tecnologies - JavaScript (Updated 180422)

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

JavaScript

TMS2824/ TMN2234/ TMI2104


Web-based System Development
2

Learning objectives
In this lesson, you will learn
 What is JavaScript? How to call?

 What is the syntax? What can JS do?

 How to access HTML DOM or DOM Event?

 How to extend functionality?


3
DHTML 

a client is a computer application, such as a web


Dynamic Behavior at the Client Side browser, that runs on a user's local computer,
smartphone, or other device, and connects to a
server as necessary.
5

What is DHTML?
 Dynamic HTML (DHTML)
 Makes possible a Web page/app to react and change in response
to the user’s actions, a.k.a “scripting”

 DHTML = HTML + CSS + JavaScript

DHTML

XHTML CSS JavaScript DOM


6

DHTML = HTML + CSS + JavaScript


 HTML defines Web content through semantic tags
(headings, paragraphs, lists, …)
 CSS defines 'rules' or 'styles' for presenting every aspect
of an HTML document
 Font (family, size, color, weight, etc.)
 Background (color, image, position, repeat)
 Position and layout (of any object on the page)

 JavaScript defines dynamic behavior


 Programming logic for interaction with the user, to handle
events, etc.
ECMAScript 2021

https://medium.com/@demiansims/javascript-a-brief-timeline-46e8943ef995
8

What is JavaScript?
 JavaScript is a scripting language developed by Netscape for
dynamic content
 Lightweight, cross-platform
 Can be used as object-oriented language system
fi le
es s to OS/
 Client-side technology NO acc

 Embedded in your HTML page


 Interpreted by the Web browser ver O S , DB
e ss to ser
Full acc
 Server-side technology
 Run by the Web server
JQuery
 Simple and flexible
9

JavaScript Advantages
 JavaScript allows interactivity such as:
 Implementing form validation
 React to user actions, e.g. handle keys
 Changing an image on moving mouse over it
 Sections of a page appearing and disappearing
 Content loading and changing dynamically
 Performing complex calculations
 Custom HTML controls, e.g. scrollable table
 Implementing AJAX functionality
10

What Can JavaScript Do?


 Can handle events

 Can read and write HTML elements and modify the DOM tree

 Can validate form data

 Can access / modify browser cookies

 Can detect the user’s browser and OS

 Can be used as object-oriented language

 Can handle exceptions

 Can perform asynchronous server calls (AJAX)


11

Example 1
first-script.html
<html>

<body>
<script type = “text/javascript”>
alert('Hello JavaScript!');
</script>
</body>

</html>
12

Example 2
small-example.html
<html>

<body>
<script>
document.write('JavaScript rulez!');
</script>
</body>

</html>

How to call/link?
14

Calling JavaScript Code


 The JavaScript code can be placed in:
1) <script></script> tag in the <head>
2) <script></script> tag in the <body> – NOT RECOMMENDED!
3) External files, linked via <script> tag in both
 Files usually have .js extension
<script type=“text/javascript” src="scripts.js”>
<!– code placed here will not be executed! -->
</script>

 Highly recommended
 The .js files get cached by the browser (speed page loads)
 Readability/modularity (separated and recombined – easier to
read/maintain)
 When using the script tag, always use the attribute name and value of
15

When is Executed?
 JavaScript code is executed during the page loading or
when the browser fires an event
 All statements are executed at page loading
 Some statements just define functions that can be called
later
 Function calls or code can be attached as "event
handlers" via tag attributes
 Executed when the event is fired by the browser
<img src="logo.gif" onclick="alert('clicked!')" />
16

Example: call JS Function from Event Handler


image-onclick.html (Internal JavaScript file)
<html>
<head>
<script>
function test (message) {
alert(message);
}
</script>
</head>

<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
17

Example 2: call External JS Files


 Using External JavaScript files: external-JavaScript.html
<html>
<head>
<script type=“text/javascript” src="sample.js">
</script>
</head> The <script> tag is always empty.
<body>
<button onclick="sample()" value="Call JavaScript
function from sample.js" />
</body>
</html>
 External JavaScript file:
function sample() {
alert('Hello from sample.js!')
} sample.js
18

Example 2: call External JS Files


 Using External JavaScript files: basicJS.html
<html>
<head>
<title>Basic JavaScript Example!</title>
<script type="text/javascript" src="example.js">
</script>
</head>
<body>
<p>This page just demonstrates including a basic JavaScript
file. The JavaScript file just tells an alert box to pop up when
the page loads.</p></body>
</html>

 External JavaScript file:


alert("This alert box was called with the onload event");
example.js
19

JavaScript’s Syntax

 Comments
 Values
 Objects
 Operators
 Control flow
 Loops
 Functions
 Errors handling
20

JavaScript Syntax
 The JavaScript syntax is similar to C# and Java
 Operators (+, *, =, !=, &&, ++, …)
 Variables (typeless)
 Conditional statements (if, else)
 Loops (for, while)
 Arrays (my_array[]) and associative arrays
(my_array['abc'])
 Functions (can return value)
 Function variables (like the C# delegates)
Comments
 Single line
 use to explain code
 // This is a single line comment use before/after code
 Similar in C++
 Multiple lines
 use to explain code
 /* This is a comment block where anything inside is
ignore by JavaScript */
 Similar in C
22

Data Types
 JavaScript data types:

 Numbers – integer, floating-point

 String – string of characters

 Boolean – true / false

 Arrays – [“one”, “two”]

 Objects – hash tables, a.k.a {key : value} pairs

 Undefined – variable without value & type


 Eg. var course;

 Empty – variable with value & type


 Eg. let course = “”;
23

Values
ES6-ECMAScript 2015
 Literal – fixed values
const counter = 100; assign value
const pi = 3.14;
 String – string of characters
var str1 = "This is a string"; Variable’s
let str2 = ‘This is another string’; name
 Array – special variable holding multiple values
var x1 = 1, x2 = 5.3, x3 = "aaa";
var my_array = [1, 5.3, "aaa"];
ES6-ECMAScript 2015
 Objects – hash tables, a.k.a {name:value}pairs
const client = {fname:"John", lname:"Doe", age:20};
let statement

 The let statement declares variables that are limited to the

scope of a block statement


 Block statement – a group of statements enclosed by curly

brackets {}
{
let myFunc = “hello”;
// myFunc can be used here
}
// myFunc CANNOT be used here
const statement

 The const statement is another way to declare variables

 let and const statements behave the same way

 The only difference: Variables declared using const statement can

NOT be reassigned and can NOT be redeclared (Error output)


try {
const x = 20;
x = 40; // throws an error
}
catch(err) {
document.write(err);
}
Number Operations
 The ‘+’ operator numbers
var x = 20;
var y = 20;
var z = a + b; // number 40
 The ‘+’ concatenate strings
var x = ‘20’;
var y = ‘20’;
var z = a + b; // string 2020
 …refer to Operators section for different kinds of
operators
Number Operation - Sample
<!DOCTYPE html> Num_operation.html
<html>
<head>
<title>Operator ‘+’</title>
</head>
<body>
<button type = "button" onclick = "myFunc()">

<script>
function myFunc() {
var x = 5;
var y = 5;
var sum = x + y; //adds x and y

alert(sum); //shows 10
}
</script>
</body>
</html>
Number Methods
 toFixed(), toPrecision()
var x = 9.656;
x.toFixed (2); // returns 9.66
x.toPrecision(2); // returns 9.7
 Number(), parseInt(), parseFloat()
Number(true); // returns 1
parseInt("10.33"); // returns 10
parseFloat("10 20 30"); // returns 10
 toExponential(), isFinite(), isInteger(), valuedOf() and more
29

String Operations
 The ‘+’ operator joins strings
var string1 = "fat ";
var string2 = "cats";
alert(string1 + string2); // fat cats

 What is "9" + 9? *If one part is char or string, output


becomes string
alert("9" + 9); // 99

 Converting string to number:

alert(parseInt("9") + 9); // 18
30

String Methods
 Length
var string1 = "This is a dummy sentence.";
string1.length; // 24 including white space
 indexOf(), lastIndexOf(), search(), match(), etc

string1.indexOf("dummy"); // output?
string1.lastIndexOf("dummy",15); // output?
string1.search("dummy"); // output?
 slice(), substring(), substr(), replace(), toUpperCase(), toLowerCase(),
concat(), trim(), and more
31

Arrays Operations and Properties


 Declaring new empty array:
var arr = new Array();

 Declaring an array holding few elements:


var arr = [1, 2, 3, 4, 5];
 Appending an element / getting the last element:
arr.push(3);
var element = arr.pop();
 Reading the number of elements (array length):
arr.length;
 Finding element's index in the array:
arr.indexOf(1);
Create Array - Sample
Array.html
<!DOCTYPE html>
<html>
<head>
<title> Create An Array </title>
</head>
<body>
<p id = "demo"></p>

<script>
var cities = ["Kuching", "Samarahan", "Bintulu"];
document.getElementById ("demo").innerHTML = cities;
</script>
</body>
</html>
Get Length of an Array- Sample
ArrayLen.html
<!DOCTYPE html>
<html>
<head>
<title> Get Array’s Length</title>
</head>
<body>
<p id = "demo"></p>

<script>
var cities = ["Kuching", "Samarahan", "Bintulu"];
document.getElementById ("demo").innerHTML = cities.lenght;
</script>
</body>
</html>
34

Array Operations
 Appending an element, getting the last element, getting
array length:
var arr = [1, 2, 3, 4, 5];

arr.push(9); // 1,2,3,4,5,9
arr.length; // 6
arr.pop(); // 1,2,3,4,5
arr.length; // 5
 Finding element's index in the array:
arr.indexOf(3); // 2
35

Array Methods
 concat()
var arr1 = ["John", "Jane"];
var arr2 = ["Ben", "Belle", "Bob"] ;
var nameDB = arr1.concat(arr2); // output?

 sort()
var fruits =["apple","orange","durian", "banana"];
fruits.sort(); // output?
document.write(fruits)

 toString(), join(), pop(), push(), shift(), unshift(), splice(),


and more
36

Standard Popup Boxes


 Alert box with text and [OK] button
 Just a message shown in a dialog box:
alert("Some text here");

 Confirmation box
 Contains text, [OK] button and [Cancel] button:
confirm("Are you sure?");

 Prompt box
 Contains text, input field with default value:
prompt ("enter amount", 10);
concat()
<!DOCTYPE html>
<html>
<body>

<p>Click the button to join two arrays.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
document.getElementById("demo").innerHTML = children;
}
</script>
</body>
</html>
sort()
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>The sort() method sorts an array alphabetically.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
fruits.sort();
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>
39

Object
 Primitive data type – store single value
 Object – complex and contain combination of the primitive
data types
 in the form of “key:value” pairs

var uni = {
name: "UNIMAS",
location: "Sarawak",
established: 1992
};
Assessing object
 By name/key
uni.established; or
uni["established"]; // 1992

 In loop
var i, txt ="";
For(i in uni){
txt += uni[i] + " ";
};

 Using Object.values()
var myArr = Object.values(uni);

 JSON.stringify()
var myStr = JSON.stringify(uni);
Object methods
 Adding method to object
uni.fullName = function(){
return this.name + " " + this.location;
};

 Accessing object method


var myUni = uni.fullName(); // UNIMAS Sarawak
 Built-in methods
myUni = myUni.toUpperCase(); // UNIMAS SARAWAK
42

Special Objects
 Math Object
 Methods – abs(), atan(), random(), and more
 Date Object
 4 ways to initiate
var d = new Date();
var d = new Date(miliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes,
seconds, miliseconds);

 Methods – getDate(), getTime(), toUTCString() and more


43

Operators

 Arithmetic
 Comparison
 Logical
 Bitwise

https://www.digitalocean.com/community/tutorials/javascript-
unary-operators-simple-and-useful
44

Arithmetic
var x = 30, y = 3;
x + y returns 33
x – y returns 27
x * y returns 90
x / y returns 10
x % y returns 0
x ** y returns 27000
x++ returns 30 (return value before increment)
++x returns 31 (return value after increment)
x-- returns 30 (return value before decrement)
--x returns 29 (return value after decrement)
-x returns -30 (negation)
+true returns 1 (convert non-numbers into numbers)
45

Comparison & Logical


var x = 5, y = 4;
var a = true, b = false;

x == y is not true
x != y is true
x > y is true
x < y is not true
x >= y is true
x <= y is not true
x === y is not true (value & type must be equal)
x !== y is true (value & type not equal)
a && b is false
a || b is true
!(a && b) is true
 for details
46

Bitwise
var x = 2, y = 3;

x & y returns 2
x | y returns 3
~x returns -3
x ^ y returns 1
x << y returns 16
x >> y returns 0
x >>> y returns 0

 for details
47

Control flow

 if…
 if…else
 if…else if
 switch

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/
Building_blocks/conditionals
48

Syntax
if (expression) { if
Execute if expression is true
}

if (expression) {
Execute if expression is true
If…else
} else {
Execute if expression is false
}

if (expression A) {
Execute if expression A is true If…else if…
} else if (expression B) {
Execute if expression B true
} else {
Execute if all expression is false
}
49

Example (if and if…else)


var unitA = 30;
var unitB = 50;

total = unitA + unitB;


if (unitA + unitB < 50) {
document.write(“Total is less than 50”);
}

If (total > 50) (


document.write(“Total is more than 50”);
} else {
document.write (“Total is less than 50”);
}
50

Example (if…else if)


 The condition may be of Boolean or integer type:

conditional-statements.html
var a = 0;
var b = true;
if (typeof(a)=="undefined" || typeof(b)=="undefined") {
document.write("Variable a or b is undefined.");
}
else if (!a && b) {
document.write("a==0; b==true;");
} else {
document.write("a==" + a + "; b==" + b + ";");
}
51

Syntax - switch
 The switch statement works like in C#:
switch (expression) {
case 1: This is how it works:
• The switch expression is evaluated once.
// do something • The value of the expression is compared
break; with the values of each case.
case 'a': • If there is a match, the associated block of
code is executed.
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
52

Switch Statement

 The getDay() method returns the weekday as a number

between 0 and 6.
 (Sunday=0, Monday=1, Tuesday=2 ..)

 This example uses the weekday number to calculate the

weekday name:
<html>
<body>
switch-statements.html 53

<p id="demo"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script> </body></html>
54

Loops

 for loop
 for…in loop
 for…of loop
 while loop
 do … while loop
55

Example (for , for…in and for…of)


for (let i = 0; i < 5; i++) { loops.html
text += "The number is " + i + "<br>";
} object
const person = {fname:"John", lname:"Doe", age:25};
let text = “”;
let x;
for (x in person) {
text += person[x];
}

const cars = [“BMW”, “Perodua”, “Proton”];


Let text = “”;
for (let x of cars) {
document.write(x + “<br >”);
}
56

Example (while and do…while)


var i = 0;
while (i < 5) {
text += "<br>The number is " + i;
i++;
}

do {
text += “<br>The number is " + i;
i++;
}
while (i < 4);
57

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For/In Loop</h2>
<p>The for/in statement loops through the properties of an object.</p>
<p id="demo"></p>

<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>
Break & Continue
 break;
 use to exit the switch() or loop

 break labelname;
 use to exit labelname code block

 continue; continue labelname;


 use to breaks ONE iteration
59

Functions

https://www.toolsqa.com/javascript/functions-in-javascript/
60

Function - declaration
 Define once and re-use
 Code structure – splitting code into parts
 Data comes in, processed, result returned
Parameters come in
function average(a, b, c) here.
{
var total; Declaring variables
total = a+b+c; is optional. Type is
return total/3; never declared.
}
Value returned
here.
61

Function - expression
 Define using expression
// function expression in ES5 Function without a name
var X = function (a, b, c)
{
return (a+b+c)/3; As function expression is
}; stored in a variable,
var Y = X(1,2,3); variable is used as
function
// arrow function in ES6
const x = (a, b, c) => (a+b+c)/3;
 Passing function as argument to another function
62

Function Arguments and Return Value


 Functions are not required to return a value

 When calling function it is not obligatory to specify all


of its arguments
 The function has access to all the arguments passed via
arguments array
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4)); functions-demo.html
63

Function - arguments
 Pass by value – not visible outside function

function square(x) { x = x * x; return x; }


var y = 10;
console.log(y); // 10 – no change

 Pass by reference – visible outside function


function myFunc(theObject) { theObject.make = ‘Perodua’;}
var mycar = {make:’Proton’, model:’Bezza’, year:2018};
var x, y;
x = mycar.make; // ‘Proton’

myFunc(mycar);
y = mycar.make; // ‘Perodua’ as changed by function
64

Function - return value


 Functions are not required to return a value

 When calling function, it is not obligatory to specify all


of its arguments
 The function has access to all the arguments passed via
arguments array

function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4)); functions-demo.html
65

Function - return value


<html> functions-demo.html
<body>
<p>Sum of all arguments:</p>
<p id="demo"></p>
<script>
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));
</script>
</body>
</html>
66

Example (function to sum 2 values)


<html> sum-of-numbers.html
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value);
value2 =
parseInt(document.mainForm.textBox2.value);
sum = value1 + value2;
document.mainForm.textBoxSum.value = sum;
}
</script>
</head>
67

Example (function to sum 2 values)


<body> sum-of-numbers.html (cont.)
<form name="mainForm">
<input type="text" name="textBox1" /> <br/>
<input type="text" name="textBox2" /> <br/>
<input type="button" value="Process"
onclick="javascript: calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>

</html>
68

Example (nested function)


<html>
<head>
<script type = "text/javascript">
function add(x, y) {
return x+y;
}

function calc() {
var result;
result = add(3,5); // can prompt for user input
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "calc()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>}
69

Error handling

 Common mistakes
 try statement
 catch statement
 throw statement
 finally statement
70

Syntax
try { Define error check
code block to check for errors
throw () Customised exception
}
catch (err) { Handle error
code block to handle errors
}
finally { Must run code
code block that always execute
}
71

Example (try…catch…throw…finally)
<script type = "text/javascript">
function calcSum() { Define error check
value1 = document.getElementById("txt1").value;
value2 = document.getElementById("txt2").value;
try{
if(value1 == "") throw ("Value 1 is empty");
if(isNaN(value1)) throw ("Value 1 is not a number");
else{
if(value2 == "") throw ("Value 2 is empty");
if(isNaN(value1)) throw ("Value 2 is not a number");
}
} Customised
catch (e){
alert("Error: " + e ); Display error
}
finally{
var sum = parseInt(value1) + parseInt(value2);
alert(sum)
}
} Must run code
</script>
72

Example (try…catch…throw…finally)
<body>
<form name="calform">
<p>Enter 1st number: <input type="text" name="textbox1"
id="txt1"><br /></p>
<p>Enter 2nd number: <input type="text" name="textbox2"
id="txt2"><br /></p>
<button onclick="calcSum()"/>Calculate two numbers</button>
</form>
</body>
</html>
List of errors
 Syntax Error
 missing ( or ), { or }
 Range Error
 invalid/out of range
 Reference Error
 reference/assignment to undefine X
 Type Error
 is not a function/object; can’t access/define/delete…
 Warning
 …common mistakes and detail of errors

JavaScript HTML DOM

https://www.tutorialspoint.com/javascript
/javascript_html_dom.htm

https://www.w3schools.com/jsref/dom_obj_document.asp
75

Document Object Model (DOM)

 Every HTML element is accessible via the JavaScript DOM API

 Most DOM objects can be manipulated by the programmer

 The event model lets a document to react when the user


does something on the page
 Advantages
 Create interactive pages
 Updates the objects of a page without reloading it (AJAX-style)
76

DOM Manipulation
 Once can access an element, can read and write its
attributes HTML element
function change(state) { with id=lamp
var lampImg = document.getElementById("lamp");
lampImg.src = "lamp_" + state + ".png";
var statusDiv = document.getElementById("statusDiv");
statusDiv.innerHTML = "The lamp is " + state";
HTML element
if(state==“on”){} with id=statusDiv
if(state==“off”){}
}
… property method
<body bgcolor="gray">
<img width="200px" height="300px" id="lamp" src="lamp_off.png"/><br/>
<div id="statusDiv"> Mouse over the switch!</div>
<img width="40px" height="60px" src="switch.png"
onmouseover="change('on')" onmouseout="change('off')" />
77

Finding Elements
 Access elements via ID
var x = document.getElementById("some_id”);

 Via tag name


var x =
document.getElementsByTagName(“some_tag”);
 Via class name
var x =
document.getElementsByClassName(“some_class”);
 Via CSS selector
var x =
document.querySelectorAll(“p.some_class”);
 Via HTML objects collection
var x = document.forms[“some_form”];
78

Common HTML Element


Properties & Methods
 Most of the properties are derived from the HTML attributes of the
tag
 E.g. id, name, href, alt, title, src, etc…

 style property – allows modifying the CSS styles of the element


 E.g. style.width, style.marginTop, style.backgroundImage

 className – the class attribute of the tag

 innerHTML – sets or returns the HTML content (inner HTML) of an


element.
 Read-only properties with information for the current element and its state
 tagName, offsetWidth, offsetHeight, scrollHeight,
scrollTop, nodeType, etc…
79

Common Element Properties (cont.)


 className – the class attribute of the tag

 innerHTML – sets or returns the HTML content (inner HTML) of


an element.
 https://www.w3schools.com/jsref/prop_html_innerhtml.asp

 Read-only properties with information for the current element and


its state
 tagName, offsetWidth, offsetHeight, scrollHeight,
scrollTop, nodeType, etc…
80

DOM Navigation

 Accessing of elements in the DOM through some tree


manipulation properties:
 parentNode
 childNodes[]
 firstChild
 lastChild
 nextSibling
 previousSibling
Example (Node relationship)
 <html> is always the root node // no parent
 <html> is the parent of <head> and <body>
 <head> is first child of <html>
 <body> is last child of <html>
 <head> is parent for <title>
 <title> has one child (text node): “”
 <body> is parent for <h1>, <p>, <table>, etc
 …

JavaScript Events

https://data-flair.training/blogs/javascript-events/
83

The HTML DOM Event Model


 JavaScript can register event handlers
 Events are fired by the Browser and are sent to the specified
JavaScript event handler function
 Can be set with HTML attributes:
<img src="test.gif" onclick="imageClicked()" />

 Can be accessed through the DOM:


var img = document.getElementById("myImage");
img.onclick = imageClicked;
84

The HTML DOM Event Model (2)

 All event handlers receive one parameter


 It brings information about the event
 Contains the type of the event (mouse click, key press,
etc.)
 Data about the location where the event has been fired
(e.g. mouse coordinates)
 Holds a reference to the event sender
 e.g. the button that was clicked
85

The HTML DOM Event Model (3)


 Holds information about the state of [Alt], [Ctrl] and
[Shift] keys
 Some browsers do not send this object, but place it in
the document.event
 Some of the names of the event’s object properties are
browser-specific
86

Common DOM Events


 Mouse events:
 onclick, onmousedown, onmouseover, onmousemove…
 Keyboard events:
 onkeypress, onkeydown, onkeyup
 Only for input fields
 Interface events:
 load, unload, resize,
 Focus events:
 onblur, onfocus,onfocusin, onfocusout, onscro;;

 Animation events:
 animationstart, animationiteration, animationend
87

Common DOM Events (2)


 Event object
 change – form element, selection or checked state changed
 submit – when form is submitted
 pause – when media is paused by user
 resize – when document view is resized
 search – when user is typing in search field
 …and more

 Miscellaneous events
 onload, onunload
 Allowed only for the <body> element
 Fires when all content on the page was loaded / unloaded
88

Example (onmousedown, onmouseup Event)


<html>
<body>
onload.html
<p id="myP" onmousedown="mouseDown()" onmouseup="mouseUp()">
Click the text! The mouseDown() function is triggered when the mouse button
is pressed down over this paragraph, and sets the color of the text to red.
The mouseUp() function is triggered when the mouse button is released, and
sets the color of the text to green.
</p>

<script>
function mouseDown() {
document.getElementById("myP").style.color = "red";
}

function mouseUp() {
document.getElementById("myP").style.color = "green";
}
</script>
</body></html>
89

onload Event – Example


 onload event
<html>
<head>
<script type="text/javascript">
function greet() {
alert("Loaded");
}
</script>
</head>
<body onload="greet()" >
</body>
</html>
90

Application Programming Interface

 Browser APIs
 DOM, AJAX, Web Audio, Geolocation,
validation, etc

 Third party APIs


 YouTube, Twitter, Facebook, Google Maps,
Paypal, etc
91

Conclusion

You should know how to…


√ explain what is JavaScript and call JavaScript in your code
√ code based on the syntax and what JavaScript can do
√ access HTML DOM and Events
√ extend functionality using APIs
?

?
?
?
Questions?
?

?
?
?
? ?

You might also like