Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java script

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

Java script

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

IT2.

2
Web Concepts
06. JavaScript 1/2 Mohammed
AbuJarour
05.11.24
* SUBJECT TO CHANGE

Plan

# Date Topic # Date Topic

1 08.10.24 Introduction to Web Technologies 7 19.11.24 Prototyping (static)


HTML 1/2
8 26.11.24 Prototyping (dynamic)
2 15.10.24 HTML 2/2
9 03.12.24 Design Thinking
3 22.10.24 CSS 1/2
10 10.12.24 WordPress 1/2
4 29.10.24 CSS 2/2
11 17.12.24 WordPress 2/2
5 05.11.24 JavaScript 1/2

6 12.11.24 JavaScript 2/2 12 07.01.25 Introduction to DevOps

Mohammed AbuJarour – JavaScript 1/2 05.11.24 2


The journey so far … and beyond

Today!

Mohammed AbuJarour – JavaScript 1/2 05.11.24 3


JavaScript
Source one.js
• JavaScript is the programming language of HTML and
function greet() {
var time = new Date(); the web.
var hours = time.getHours();
var greeting = "Good morning!"; • JavaScript is one of the 3 languages all web
if (hours >= 12 && hours < 18)
greeting = "Good afternoon!";
developers must learn:
else if (hours >= 18 && hours <= 23)
greeting = "Good evening!"; • HTML to define the content of web pages

document.getElementById("greeting").innerHTML = greeting; • CSS to specify the layout of web pages


}
• JavaScript to program the behavior of web pages

• Many desktop and server programs use JavaScript, as


well. For example, Node.js, MongoDB, CouchDB, etc.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 4


1) Introduction

5
JavaScript – history
Version Official Name
• JavaScript was invented by Brendan Eich from 1 ECMAScript 1 (1997)
Netscape (web browser) in 1995 2 ECMAScript 2 (1998)

• JavaScript became an ECMA* standard in 1997 3 ECMAScript 3 (1999)


4 ECMAScript 4
• ECMAScript (ES) is the official name of the language 5 ECMAScript 5 (2009)
• From 2015 ECMAScript (ES6) is named by year, e.g., 5.1 ECMAScript 5.1 (2011)
ECMAScript 2015 6 ECMAScript 2015
7 ECMAScript 2016
• Browser Support:
8 ECMAScript 2017
o ECMAScript 3 is fully supported in all browsers. 9 ECMAScript 2018
o ECMAScript 5 is fully supported in all modern browsers. 10 ECMAScript 2019
* ECMA: European Computer Manufacturers Association

Mohammed AbuJarour – JavaScript 1/2 05.11.24 6


JavaScript – today
• ECMAScript describes the language syntax and basic objects
• The Document Object Model (DOM) describes methods and
interfaces for working with the content of a web page (document)
• The Browser Object Model (BOM) describes the methods and JavaScript
interfaces for interacting with the browser
ECMAScript DOM BOM

Source: Professional JavaScript for Web Developers –Nicholas C. Zakas

Mohammed AbuJarour – JavaScript 1/2 05.11.24 7


JavaScript is not only a client-side language!

Client-side Server-side
• Browser support • Promoted by Gmail and Google
• User setting Maps (client-side)
• Nodejs

Mohammed AbuJarour – JavaScript 1/2 05.11.24 8


What can JavaScript do?
1. JavaScript can change HTML content
Client-side
2. JavaScript can change HTML attribute values

3. JavaScript can change HTML styles (CSS)

4. JavaScript can hide HTML elements

5. JavaScript can show HTML elements

6. React to user actions, run on mouse clicks, pointer movements, key presses.

7. Send requests over the network to remote servers, download and upload files

8. Get and set cookies, ask questions to the visitor, show messages

9. Remember the data on the client-side (“local storage”)

Mohammed AbuJarour – JavaScript 1/2 05.11.24 9


What can NOT JavaScript do? Client-side

1.JavaScript on a webpage has no


direct access to OS functions: It may
Browser Engine
not access arbitrary files on the hard
JavaScript
disk or execute programs.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 10


What can NOT JavaScript do?
Client-side

2. Same Origin Policy: Different


tabs/windows generally do not know
about each other.
o JavaScript from one page may not access the
other if they come from different sites / origins
(from a different domain, protocol or port).

Mohammed AbuJarour – JavaScript 1/2 05.11.24 11


What can NOT JavaScript do?
Client-side

3. JavaScript can easily communicate


over the network to the server
where the current page came from.
But its ability to receive data from
other sites/domains is disabled.
o Though possible, it requires explicit
agreement (expressed in HTTP headers)
from the remote side.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 12


2) Basics
1
3
Add JavaScript to a webpage
Internal External
<html> <html>

<head> <head>
<title>JavaScript 101</title> <title>JavaScript 101</title>
<script> <script src="js-sample-01.js"></script>
function greet() {
/* ... */
}
</script>
</head> </head>

<body onload="greet();"> <body onload="greet();">


<h1>Welcome to JavaScript</h1> <h1>Welcome to JavaScript</h1>
<p>This is how you can use JavaScript.</p> <p>This is how you can use JavaScript.</p>
<p id="greeting"></p> <p id="greeting"></p>
</body> </body>

</html> </html>

Mohammed AbuJarour – JavaScript 1/2 05.11.24 14


Putting it all together
Project structure <html>

<head>
one.html <title>Page Title</title>
<link rel="stylesheet" type="text/css" href="one.css">
<script src="one.js"></script>
</head>

<body onload="greet();">
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p id="greeting"></p>
</body>

</html
one.css
body {
background-color: lightblue;
one.js
} function greet() {
var time = new Date();
h1 { var hours = time.getHours();
color: white; var greeting = "Good morning!";
} if (hours >= 12 && hours < 18)
greeting = "Good afternoon!";
p{ else if (hours >= 18 && hours <= 23)
font-size: 20px; greeting = "Good evening!";
}
document.getElementById("greeting").innerHTML = greeting;
}

Mohammed AbuJarour – JavaScript 1/2 05.11.24 15


JavaScript in <head> or <body>
<html>
<head>
<title>JavaScript 101</title> • In HTML, JavaScript code is inserted
<script> between <script> and </script> tags.
function greet() { • You can place any number of scripts in
/* ... */ an HTML document.
}
• Scripts can be placed in the <body>, or
</script>
in the <head> section of an HTML page,
</head>
or in both.
<body onload="greet();">
<!-- ... -->
</body>
</html>

Mohammed AbuJarour – JavaScript 1/2 05.11.24 16


JavaScript in <head> or <body>
Common
practice
<html> <html>

<head> <head>
<title>JavaScript 101</title> <title>JavaScript 101</title>
<script> </head>
function greet() {
/* ... */ <body onload="greet();">
} <!-- ... -->
</script> <script>
</head> function greet() {
/* ... */
<body onload="greet();"> }
<!-- ... --> </script>
</body> </body>

</html> </html>

Mohammed AbuJarour – JavaScript 1/2 05.11.24 17


External JavaScript

<html> • External scripts are practical


<head> when the same code is used
<title>JavaScript 101</title> in many different web pages
<script src="js-sample-01.js"> </script> (reusability).
</head> • JavaScript files have the file
</html> extension .js.
• To add an external script,
reference that script file
in the src (source) attribute of
a <script> tag

Mohammed AbuJarour – JavaScript 1/2 05.11.24 18


External JavaScript

• You can place an external script reference in <head> or <body>.


• The script will behave as if it was located exactly where the <script> tag is located.
• External scripts can be referenced with a full URL or with a path relative to the
current web page.

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script>

Mohammed AbuJarour – JavaScript 1/2 05.11.24 19


External JavaScript

• External JavaScript advantages

✓separate HTML (content) and code

✓make HTML and JavaScript easier to read and maintain

✓speed up page loads due to cached JavaScript files (in browser)

Mohammed AbuJarour – JavaScript 1/2 05.11.24 20


How does it work?

• Web browsers have built-in engines to run JavaScript


o V8 used by Google Chrome and Node.js
o SpiderMonkey used by Firefox
o JavaScriptCore used by Safari/WebKit.
o Chakra was used by Microsoft Edge (JScript engine used in Internet Explorer) → switched
recently to V8.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 21


How does it work?

• JavaScript engines enhance the language by providing a rich environment,


offering also an event-driven platform for JavaScript.
• In an event-driven architecture there are two actors: the producer (event
emitter) and the consumer (event target).
• JavaScript in the browser can interact with HTML elements, which are event
emitters
• JavaScript functions registered as consumers are the event targets

Mohammed AbuJarour – JavaScript 1/2 05.11.24 22


How does it work?

Browser’s JavaScript Engine


Event consumer / target
function greet() {
var time = new Date();
var hours = time.getHours();
var greeting = "Good morning!";
if (hours >= 12 && hours < 18)
greeting = "Good afternoon!";
else if (hours >= 18 && hours <= 23)
greeting = "Good evening!";

document.getElementById("greeting").innerHTML = greeting;
}

Event

Event producer / emitter


Event result/ post-state

Mohammed AbuJarour – JavaScript 1/2 23


05.11.24
3) Syntax
2
4
Functions

• Enable code reusability – define the code once


and use it many times.
• A JavaScript function is a block of code designed
to perform a particular task.
• A JavaScript function is executed when a caller
(e.g., event producer/emitter) invokes it (calls it):
o When an event occurs (when a user clicks a button)
o When it is invoked (called) from JavaScript code
o Automatically (self invoked)

Mohammed AbuJarour – JavaScript 1/2 05.11.24 25


Functions

• A JavaScript function is defined with • The parentheses may include


the function keyword, followed by parameter names separated by
a name, followed by parentheses (). commas:
• Function names can contain letters, (parameter1, parameter2, …)
digits, underscores, and dollar signs.
• When JavaScript reaches
a return statement, the function will
stop executing.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 26


Functions

• Function arguments are the values • Variables declared within a


received by the function when it is JavaScript function are local to the
invoked. function.
• Inside the function, the arguments • The function has full access to outer
(the parameters) behave as local variables
variables.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 27


Functions
<body> <head>
<h1>Welcome to JavaScript</h1> <script>

<p> var count = 0;

This convertor converts from Fahrenheit to Celsius.


function toCelsius(fahrenheit) {
</p>
return (5 / 9) * (fahrenheit - 32);
<p>
}
<label for="fahrenheit">Fahrenheit:</label>

<input type="number" id="f" name="fahrenheit"> function convert() {


<button onclick="convert();"> var f = document.getElementById('f').value;
var c = toCelsius(f);
Convert to Celsius
count++;
</button>
document.getElementById("celsius").innerHTML = c;
</p>
document.getElementById("stats").innerHTML = count;
<p> <span id="celsius"></span> C</p> }
<p> Used <span id="stats"></span> times.</p> </script>
</body> </head>

Mohammed AbuJarour – JavaScript 1/2 05.11.24 28


JavaScript events

• An event represents a change in the state


• JavaScript can handle events in HTML pages
• An HTML event can be something the browser does, or something a user does:
o An HTML web page has finished loading
o The value of an HTML input field was changed <button onclick="convert();">
Convert to Celsius
o An HTML button was clicked </button>
o The browser window has been resized

• HTML allows event handler attributes to be added to HTML elements.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 29


Common HTML events

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

Mohammed AbuJarour – JavaScript 1/2 05.11.24 30


JavaScript variables

• All JavaScript variables must be identified with unique names.


• The general rules for constructing names for variables (unique identifiers) are:
o Names can contain letters, digits, underscores, and dollar signs.
o Names must begin with a letter, $ or _ (underscore)
o Names are case sensitive (fname and fName are different variables)
o Reserved words (like JavaScript keywords) cannot be used as names

Mohammed AbuJarour – JavaScript 1/2 05.11.24 31


JavaScript variables

• JavaScript can handle many types of data – later


• You declare a JavaScript variable with the var keyword

var f = document.getElementById('f').value;
var c = toCelsius(f);

Mohammed AbuJarour – JavaScript 1/2 05.11.24 32


JavaScript operators
JavaScript Arithmetic Operators JavaScript Type Operators
Operator Description Operator Description

+ Addition typeof Returns the type of a variable


- Subtraction
instanceof Returns true if an object is an
* Multiplication instance of an object type
** Exponentiation (ES2016)

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement

Mohammed AbuJarour – JavaScript 1/2 05.11.24 33


JavaScript operators
JavaScript Comparison Operators JavaScript Logical Operators
Operator Description Operator Description
== equal to && logical and
=== equal value and equal type
|| logical or
!= not equal
!== not equal value or not equal type ! logical not

> greater than


< less than
>= greater than or equal to
<= less than or equal to
? ternary operator var result = (grade > 50) ? "Pass" : "Fail";

Mohammed AbuJarour – JavaScript 1/2 05.11.24 34


JavaScript types – primitive

• JavaScript has dynamic types → The same variable can be used to hold different
data types

var x; // Now x is undefined


x = 5; // Now x is a Number
x = "John"; // Now x is a String

Mohammed AbuJarour – JavaScript 1/2 05.11.24 35


JavaScript types – primitive

• Strings are written with quotes. You can use single or double quotes.
• Numbers can be written with or without decimals
• Booleans can only have two values: true or false.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 36


JavaScript types – empty

• In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.

var car; // Value is undefined, type is undefined

• Any variable can be emptied, by setting the value to undefined. The type will also
be undefined.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 37


JavaScript types – empty

• An empty value has nothing to do with undefined.


• An empty string has both a legal value and a type.

var name = ""; // The value is "", the typeof is "string"

Mohammed AbuJarour – JavaScript 1/2 05.11.24 38


JavaScript types – empty

• In JavaScript null is “nothing”. The data type of null is an object.


• undefined and null are equal in value but different in type

typeof undefined // undefined


typeof null // object

null === undefined // false


null == undefined // true

Mohammed AbuJarour – JavaScript 1/2 05.11.24 39


JavaScript numbers

• JavaScript Numbers are always 64-bit floating point


• JavaScript will try to convert numeric strings to numbers in all numeric operations
except in addition (concatenation)

var a = "100";
var b = "10";
var c = a / b; // c will be 10
var d = a * b; // d will be 1000
var e = a - b; // e will be 90
var f = a + b; // f will not be 110 (It will be 10010)

Mohammed AbuJarour – JavaScript 1/2 05.11.24 40


JavaScript numbers –
converting variables to numbers
Method Description
Number() Returns a number, converted from its argument.

parseFloat() Parses its argument and returns a floating-point number

parseInt() Parses its argument and returns an integer

var a = "100";
var b = "10";
var c = a / b; // c will be 10
var d = a * b; // d will be 1000
var e = a - b; // e will be 90
var f = a + b; // f will not be 110 (It will be 10010)
var g = Number(a) + Number(b); // g will be 110

Mohammed AbuJarour – JavaScript 1/2 05.11.24 41


JavaScript numbers

• NaN is a JavaScript reserved word indicating that a value is not a legal number

• isNaN() is a global JavaScript function that checks whether a value is not a legal

number

• Infinity (or -Infinity) is the value JavaScript will return if you calculate a number

outside the largest possible number

Mohammed AbuJarour – JavaScript 1/2 05.11.24 42


Note:
string.length is a property
String methods not a method
Method Description
charAt() Returns the character at the specified index (position)
concat() Joins two or more strings, and returns a new joined strings
trim() Removes whitespace from both ends of a string
startsWith() Checks whether a string begins with specified characters
endsWith() Checks whether a string ends with specified string/characters
includes() Checks whether a string contains the specified string/characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
replace() Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced
search() Searches a string for a specified value, or regular expression, and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLowerCase() Converts a string to lowercase letters
toUpperCase() Converts a string to uppercase letters
valueOf() Returns the primitive value of a String object
toString() Returns the value of a String object

Mohammed AbuJarour – JavaScript 1/2 05.11.24 43


JavaScript Date object
• By default, JavaScript will use the browser’s time zone and display a date as a full
text string
• Date objects are created with the new Date() constructor.

var today = new Date();


document.getElementById("dateDisplay").innerHTML = today;
//Tue Nov 05 2024 08:20:00 GMT+0100 (Central European Standard Time)
document.getElementById("dateDisplay").innerHTML = today.toDateString();
//Thu June 8 2023

Mohammed AbuJarour – JavaScript 1/2 05.11.24 44


JavaScript Date object
• There are 4 ways to create a new date object:

var today = new Date();


var myBirthday = new Date(1980, 11, 24, 10, 33, 30, 0);
//new Date(year, month, day, hours, minutes, seconds, milliseconds)
var myGraduationDate = new Date("October 13, 2000 11:13:00");
// new Date(string)
var plusTenYears = new Date(10*365.25*24*60*60*1000);
//new Date(milliseconds): 01 January 1970 plus + milliseconds

Mohammed AbuJarour – JavaScript 1/2 05.11.24 45


JavaScript Date methods
Method Description Method Description
getFullYear() Get the year as a four digit number setDate() Set the day as a number (1-31)
(yyyy)
getMonth() Get the month as a number (0-11) setFullYear() Set the year
getDate() Get the day as a number (1-31) (optionally month and day)

getHours() Get the hour (0-23) setHours() Set the hour (0-23)
getMinutes() Get the minute (0-59) Set the milliseconds (0-999)
setMilliseconds()
getSeconds() Get the second (0-59)
setMinutes() Set the minutes (0-59)
getMilliseconds() Get the millisecond (0-999)
setMonth() Set the month (0-11)
getTime() Get the time (milliseconds since
January 1, 1970) setSeconds() Set the seconds (0-59)

getDay() Get the weekday as a number (0-6) setTime() Set the time (milliseconds since
Get the time. ECMAScript 5. January 1, 1970)
Date.now()

Mohammed AbuJarour – JavaScript 1/2 05.11.24 46


JavaScript Math object
Method Description floor(x) Returns x, rounded downwards to the nearest
abs(x) Returns the absolute value of x integer
acos(x) Returns the arccosine of x, in radians log(x) Returns the natural logarithm (base E) of x
acosh(x) Returns the hyperbolic arccosine of x max(x, y, z, ..., n) Returns the number with the highest value
asin(x) Returns the arcsine of x, in radians
asinh(x) Returns the hyperbolic arcsine of x min(x, y, z, ..., n) Returns the number with the lowest value
atan(x) Returns the arctangent of x as a numeric value
between -PI/2 and PI/2 radians pow(x, y) Returns the value of x to the power of y

atan2(y, x) Returns the arctangent of the quotient of its random() Returns a random number between 0 and 1
arguments round(x) Rounds x to the nearest integer
atanh(x) Returns the hyperbolic arctangent of x Returns the sine of x (x is in radians)
sin(x)
cbrt(x) Returns the cubic root of x
sinh(x) Returns the hyperbolic sine of x
ceil(x) Returns x, rounded upwards to the nearest
integer sqrt(x) Returns the square root of x
cos(x) Returns the cosine of x (x is in radians) tan(x) Returns the tangent of an angle
cosh(x) Returns the hyperbolic cosine of x tanh(x) Returns the hyperbolic tangent of a number
x
exp(x) Returns the value of E trunc(x) Returns the integer part of a number (x)

05.11.24 Mohammed AbuJarour – JavaScript 1/2 47


4) Control Flows
4
8
JavaScript conditional statements
JavaScript has the following conditional
statements: function points2grade(points) {
var grade;
• if specifies a block of code to be if (points < 50) {
executed, if a specified condition is true grade = "F";
} else if (points < 70) {
• else specifies a block of code to be grade = "C";
executed, if the same condition is false } else if (points < 85) {
grade = "B";
• else if specifies a new condition to test, }
if the first condition is false else {
grade = "A";
• switch specifies many alternative blocks }
return grade;
of code to be executed
}

Mohammed AbuJarour – JavaScript 1/2 05.11.24 49


JavaScript conditional statements
var todayNumber = new Date().getDay();
switch (todayNumber) {
• switch statement selects one of many case 0:
code blocks to be executed 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;
default:
day = "Saturday";
}
Mohammed AbuJarour – JavaScript 1/2 05.11.24 50
JavaScript Loops

• Loops can execute a block of code a number of times.


• JavaScript supports different kinds of loops:
• for - loops through a block of code a number of times
• for/in - loops through the properties of an object
• for/of - loops through the values of an iterable object
• while - loops through a block of code while a specified condition is true
• do/while - also loops through a block of code while a specified condition is true

Mohammed AbuJarour – JavaScript 1/2 05.11.24 51


JavaScript Loops – for
var i;
var text = "";
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
//"The number is 0<br>The number is 1<br>The number is 2<br>The number is 3<br>The number is 4<br>"

Mohammed AbuJarour – JavaScript 1/2 05.11.24 52


JavaScript loops – while & do/while
var text = ""; var text = "";
var i = 0; var i = 0;
while (i < 5) {
do{
text += "The number is " + i + " <br>";
text += "The number is " + i + " <br>";
i++;
} i++;
//The number is 0 <br>The number is 1 <br> } while (i < 5);
The number is 2 <br>The number is 3 <br>
The number is 4 <br>
//The number is 0 <br>The number is 1 <br> The number is 2
<br>The number is 3 <br> The number is 4 <br>

Mohammed AbuJarour – JavaScript 1/2 05.11.24 53


JavaScript break and continue
var items = ["Mac", "Samsung", "iPhone"]; • The break statement “jumps out” of a
items[1] = undefined; loop.
var index = -1; • The continue statement “jumps over”
var query = "iPhone"; one iteration in the loop
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item == undefined)
continue;
if (item == query) {
index = i;
break;
}
}

Mohammed AbuJarour – JavaScript 1/2 05.11.24 54


JavaScript errors – throw and try to catch
function myFunction() {
var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if (x == "") throw "is empty";
if (isNaN(x)) throw "is not a number";
x = Number(x);
if (x > 100) throw "is too high";
if (x < 0) throw "is too low";
}
catch (err) {
message.innerHTML = "Error: " + err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}

Mohammed AbuJarour – JavaScript 1/2 05.11.24 55


5) JavaScript HTML DOM
5
6
JavaScript HTML DOM

• DOM stands for


Document Object Model
• The browser creates a
Document Object Model of
each page it loads
• The HTML DOM model is
constructed as a tree of objects

Mohammed AbuJarour – JavaScript 1/2 05.11.24 57


DOM & JavaScript
• DOM is a programming interface through which JavaScript can:
o change all the HTML elements in the page
o change all the HTML attributes in the page
o change all the CSS styles in the page
o remove existing HTML elements and attributes
o add new HTML elements and attributes
o react to all existing HTML events in the page
o create new HTML events in the page

The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

Mohammed AbuJarour – JavaScript 1/2 05.11.24 58


DOM programming interface
Method
function validateInput() { (action) • In the DOM, all HTML elements
are defined as objects.
var message = document.getElementById("message");
• The programming interface is the
Property
(value) – set properties and methods of each
message.innerHTML = ""; object.
var x = document.getElementById("userInput").value; • A property is a value that you
// ...
can get or set (like changing
Method Property the content of an HTML
} (action) (value) – get element).
• A method is an action you can
do (like add or deleting an
HTML element)
Mohammed AbuJarour – JavaScript 1/2 05.11.24 59
Basic DOM capabilities
• In addition to document.getElementById(id), document.getElementsByTagName(name)
and document.getElementsByClassName(name) can be used to find HTML elements

Mohammed AbuJarour – JavaScript 1/2 05.11.24 60


Basic DOM capabilities

• HTML elements can be changed using:


• element.innerHTML = new html content: change the inner HTML of an element
• element.attribute = new value: change the attribute value of an HTML element
• element.style.property = new style: change the style of an HTML element

Mohammed AbuJarour – JavaScript 1/2 05.11.24 61


Basic DOM capabilities

• Adding and Deleting Elements


• document.createElement(element) creates a new HTML element
• document.removeChild(element) removes an existing HTML element
• document.appendChild(element) adds an HTML element
• document.replaceChild(new, old) replaces an HTML element

Mohammed AbuJarour – JavaScript 1/2 05.11.24 62


HTML objects
Property Description
document.anchors Returns all <a> elements that have a name attribute
document.body Returns the <body> element
document.documentElement Returns the <html> element
document.documentURI Returns the URI of the document
document.forms Returns all <form> elements
document.head Returns the <head> element
document.images Returns all <img> elements
document.links Returns all <area> and <a> elements that have a href attribute
document.scripts Returns all <script> elements
document.title Returns the <title> element
document.URL Returns the complete URL of the document

Mohammed AbuJarour – JavaScript 1/2 05.11.24 63


DOM & CSS
function validateInput() {
var message = document.getElementById("message");
message.innerHTML = "";
var x = document.getElementById("userInput").value;
try {
if (x == "") throw "Input is empty";
if (isNaN(x)) throw "Input '" + x + "' is not a number";
x = Number(x);
if (x > 100) throw x + " is too high";
else if (x < 0) throw x + " is too low";
else {
message.innerHTML = x + " is a valid input :)";
message.style.color = "green";
}
}
catch (err) {
message.innerHTML = "Error: " + err + ".";
message.style.color = "red";
}
// ...
}

Mohammed AbuJarour – JavaScript 1/2 05.11.24 64


6) Debugging
6
5
Developer tools
• Developer tools allow us to see errors, run commands, examine variables, and
much more.
• They can be opened with F12 for most browsers on Windows.
• Chrome for Mac needs Cmd+Opt+J, Firefox Cmd+Opt+K,
Safari: Cmd+Opt+C (need to enable first).

Mohammed AbuJarour – JavaScript 1/2 05.11.24 66


Developer tools
• Use console.log() to display debug messages in the console

Mohammed AbuJarour – JavaScript 1/2 05.11.24 67


JavaScript display possibilities

JavaScript can “display” data in different ways:


• Writing into an HTML element, using innerHTML
• Writing into the HTML output using document.write()
• Writing into an alert box, using window.alert()
• Writing into the browser console, using console.log()

Mohammed AbuJarour – JavaScript 1/2 05.11.24 68


References

• https://www.w3schools.com/js/default.asp
• https://javascript.info/
• https://www.valentinog.com/blog/event/
• Professional JavaScript for Web Developers –Nicholas C. Zakas

Mohammed AbuJarour – JavaScript 1/2 05.11.24 69


7) Exercises
7
0
Exercise 1: Guess what?

• Create a simple web page where a secret (random integer) is generated


(between 1 and 20) and the user must guess this secret. If the user’s guess is
correct, the user gains 10 points, otherwise, the user loses one point.
• The score must be shown always
• The web pages must enable the user to generate a new secret
• Once the guess is checked, its input field must be cleared
• When the user’s guess is correct, the user must be notified accordingly

Mohammed AbuJarour – JavaScript 1/2 05.11.24 71


Exercise 2: Simple Calculations

Mohammed AbuJarour – JavaScript 1/2 05.11.24 72


Exercise 3: Dynamic form

Mohammed AbuJarour – JavaScript 1/2 05.11.24 73


Exercise 4: Captcha

• Generate a random captcha


• Verify the provided values by the
user

Mohammed AbuJarour – JavaScript 1/2 05.11.24 74

You might also like