[go: up one dir, main page]

0% found this document useful (0 votes)
5 views51 pages

Unit 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views51 pages

Unit 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

UNIT 2 – JAVASCRIPT

Javascript:
JavaScript is the scripting language of the Web.
JavaScript is the world's most popular programming language.

The <script> Tag


In HTML, JavaScript code is inserted between <script> and </script> tags.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both
Eg:
<!DOCTYPE html>
<html>
<head>
<script>
alert("My First JavaScript");
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
</body>
</html>

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>
Output:

JavaScript Output

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().

Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML
content
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Output:
Using document.write()
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

Output:

Using window.alert()
Eg:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>

Output:

Using console.log()
Eg:
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>

Output:

JavaScript Variables
variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.

Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are undeclared.</p>
<p>They are automatically declared when first used.</p>
<p id="demo"></p>
<script>
x = 5;
y = 6;
z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>

Output:
Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
Output:

The let keyword

Variables declared with let have Block Scope


Variables declared with let must be Declared before use
Variables declared with let cannot be Redeclared in the same scope

Block Scope
JavaScript had Global Scope and Function Scope.
let and const.keywords provided Block Scope in JavaScript:

Eg:
{
let x = 2;
}
// x can NOT be used here

Global Scope
Variables declared with the var always have Global Scope.
Variables declared with the var keyword can NOT have block scope:
Eg:
{
var x = 2;
}
// x CAN be used here
Cannot be Redeclared
Variables defined with let can not be redeclared.
You can not redeclare a variable declared with let.
Eg:
let x = 10;
// Here x is 10

{
let x = 2;
// Here x is 2
}

// Here x is 10

Eg:
var x = 10;
// Here x is 10

{
var x = 2;
// Here x is 2
}

// Here x is 2

The const keyword:


Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope
Eg:
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error

JavaScript const variables must be assigned a value when they are declared:
Eg:
const PI = 3.14159265359;
Incorrect
const PI;
PI = 3.14159265359;

JavaScript Comments
Single Line Comments
Single line comments start with //.
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.

JavaScript Identifiers / Names


Identifiers are JavaScript names.
Identifiers are used to name variables and keywords, and functions.
The rules for legal names are the same in most programming languages.
A JavaScript name must begin with:
● A letter (A-Z or a-z)

● A dollar sign ($)


● Or an underscore (_)
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character of the identifiers
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables

Eg:
let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";

first-name, last-name, master-card, inter-city. (not allowed)


Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
firstName, lastName, masterCard, interCity.

JavaScript Data Types


1.String
2.Number
3.Boolean
4.Undefined
5.Null
6.Symbol
7.Object

// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;

// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");

A javascript variable can hold any type value

Eg:
let x = 16 + "Volvo";
//16Volvo

JavaScript evaluates expressions from left to right.


let x = 16 + 4 + "Volvo"
//20Volvo
JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

let x = "Volvo" + 16 + 4;
// Volvo164
the first operand is a string, all operands are treated as strings.

let x; // Now x is undefined


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

// Using double quotes:


let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = 'Volvo XC60';

// Single quote inside double quotes:


let answer1 = "It's alright";

// Single quotes inside double quotes:


let answer2 = "He is called 'Johnny'";

// Double quotes inside single quotes:


let answer3 = 'He is called "Johnny"';
Output:
It's alright
He is called 'Johnny'
He is called "Johnny"

All JavaScript numbers are stored as decimal numbers (floating point).


// With decimals:
let x1 = 34.00;

// Without decimals:
let x2 = 34;
Exponential Notation
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123

Most programming languages have many number types:

Whole numbers (integers):


byte (8-bit), short (16-bit), int (32-bit), long (64-bit)

Real numbers (floating-point):


float (32-bit), double (64-bit).

Javascript numbers are always one type: double (64-bit floating point).

JavaScript Booleans

Booleans can only have two values: true or false.


let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false

JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.

Syntax:
const array_name = [item1, item2, ...];

Eg:
const cars = ["Saab", "Volvo", "BMW"];

Array indexes are zero-based, which means the first item is [0], second is [1],
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Array indexes are zero-based, which means the first item is [0].</p>
<p id="demo"></p>
<script>
const cars = ["Saab","Volvo","BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html>
Using the JavaScript Keyword new
const cars = new Array("Saab", "Volvo", "BMW");

Changing an Array Element


Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>

Converting an Array to a String


The JavaScript method toString() converts an array to a string of (comma separated) array
values.

Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The toString() Method</h2>
<p>The toString() method returns an array as a comma separated string:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>
</body>
</html>

Array Properties and Methods


cars.length // Returns the number of elements
cars.sort() // Sorts the array

Eg:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
//4

Accessing the Last Array Element


Eg:
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits[fruits.length-1];
</script>

//Mango
Adding Array Elements
The easiest way to add a new element to an array is using the push() method
Eg:
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits

<script>
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon";

let fLen = fruits.length;


let text = "";
for (i = 0; i < fLen; i++) {
text += fruits[i] + "<br>";
}
Output:
Banana
Orange
Apple
undefined
undefined
undefined
Lemon

Eg:
<script>
var points =[40];
document.getElementById("demo").innerHTML = points[0];
</script>
Output:
40

<script>
var points = new Array(40);
document.getElementById("demo").innerHTML = points[0];
</script>
Output:
Undefined

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = typeof fruits;
</script>
Output:
object

JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
Eg:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + "
years old.";
</script>
</body>
</html>
Output:
John is 50 years old.

The typeof Operator


the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression

typeof "" // Returns "string"


typeof "John" // Returns "string"
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"

Undefined

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

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

Empty Values
An empty value has nothing to do with undefined.

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

let car = ""; // The value is "", the typeof is "string"

JavaScript Functions
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}

Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
● When an event occurs (when a user clicks a button)
● When it is invoked (called) from JavaScript code
● Automatically (self invoked)

Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller"

Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>

Javascript Operators:

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Operat Exam Result Result
Description
or ple of x of y
+ Addition x=y+2 7 5
- Subtraction x=y-2 3 5
* Multiplication x=y*2 10 5
/ Division x=y/2 2.5 5
Modulus (division
% x=y%2 1 5
remainder)
x=++y 6 6
++ Increment
x=y++ 5 6
x=--y 4 4
-- Decrement
x=y-- 5 4

JavaScript Assignment Operators


Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
Operat Exam Same Res
or ple As ult
= x=y x=5
x=1
+= x+=y x=x+y
5
-= x-=y x=x-y x=5
*= x*=y x=x*y x=5
0
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

JavaScript Comparison Operators


Comparison operators are used in logical statements to determine equality or difference
between variables or values.
Given that x=5, the table below explains the comparison operators:
Operat Compari Retur
Description
or ng ns
x==8 false
== equal to
x==5 true
exactly equal to (equal value and equal x==="5" false
===
type) x===5 true
!= not equal x!=8 true
not equal (different value or different x!=="5" true
!==
type) x!==5 false
> greater than x>8 false
< less than x<8 true
>= greater than or equal to x>=8 false
<= less than or equal to x<=8 true

Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operat Descripti
Example
or on
(x < 10 && y > 1) is
&& and
true
|| or (x==5 || y==5) is false
! not !(x==y) is true

JavaScript If...Else Statements


Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
● if statement - use this statement to execute some code only if a specified condition is
true
● if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
● if...else if....else statement - use this statement to select one of many blocks of code to be
executed
● switch statement - use this statement to select one of many blocks of code to be
executed

If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax Make a "Good day" greeting if
if (condition) the time is less than 20:00:
{ if (time<20)
code to be executed if condition is true {
} x="Good day";
Note that if is written in lowercase letters. Using }
uppercase letters (IF) will generate a JavaScript error! The result of x will be:
Good day

If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.
Syntax If the time is less than 20:00, you will get a "Good day"
if (condition) greeting, otherwise you will get a "Good evening" greeting
{ if (time<20)
code to be executed if {
condition is true x="Good day";
} }
else else
{ {
code to be executed if x="Good evening";
condition is not true }
} The result of x will be:
Good day

If...else if...else Statement


Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax if (time<10)
if (condition1) {
{ x="Good morning";
code to be executed if condition1 is true }
} else if (time<20)
else if (condition2) {
{ x="Good day";
code to be executed if condition2 is true }
} else
else {
{ x="Good evening";
code to be executed if neither condition1 nor condition2 is }
true The result of x will be:
} Good day

The JavaScript Switch Statement

Use the switch statement to select one of many blocks of code to be executed.
Syntax var day=new Date().getDay();
switch(n) switch (day)
{ {
case 1: case 0:
execute code block 1 x="Today is Sunday";
break; break;
case 2: case 1:
execute code block 2 x="Today is Monday";
break; break;
default: case 2:
code to be executed if n is different from case 1 and x="Today is Tuesday";
2 break;
} case 3:
x="Today is Wednesday";
break;
case 4:
x="Today is Thursday";
break;
case 5:
x="Today is Friday";
break;
case 6:
x="Today is Saturday";
break;
}

The default Keyword


Use the default keyword to specify what to do if there is no match:

Example
If the day is NOT Saturday or Sunday, then write a default message:

var day=new Date().getDay();


switch (day)
{
case 6:
x="Today is Saturday";
break;
case 0:
x="Today is Sunday";
break;
default:
x="Looking forward to the Weekend";
}
The result of x will be:
Looking forward to the Weekend

JavaScript Loops
Different Kinds of Loops
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


● 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

The For Loop


The for loop is often the tool you will use when you want to create a loop.

syntax:
for (statement 1; statement 2; statement 3)
{
the code block to be executed
}
Eg:
for (var i=0; i<5; i++)
{
x=x + "The number is " + i + "<br>";
}

<script> <script>
cars=["RENAULT","Tata","Maruti","Fo cars=["RENAULT","Tata","Maruti","Fo
rd"]; rd"];
for (var i=0,l=cars.length; i<l; i++) var i=2,len=cars.length;
{ for (; i<len; i++)
document.write(cars[i] + "<br>"); {
} document.write(cars[i] + "<br>");
</script> }
</script>

The For/In Loop


The JavaScript for/in statement loops through the properties of an object:
<html>
<body>
<p>Click the button to loop through the properties of an object named
"person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var txt="";
var person={fname:"Suresh",lname:"M",age:35};

for (var x in person)


{
//txt=txt + person[x];
document.write(x);
document.write(person[x]);
}
//document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html></body>
Output
The While Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax while (i<5)
while (condition) {
{ x=x + "The number is " + i + "<br>";
code block to be i++;
executed }
}

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax do
do {
{ x=x + "The number is " + i + "<br>";
code block to be i++;
executed }
} while (i<5);
while (condition);

The Break Statement

You have already seen the break statement used in an earlier chapter of this tutorial. It was used
to "jump out" of a switch() statement.

The break statement can also be used to jump out of a loop.

for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

for (i=0;i<=10;i++)
{
if (i==3) continue; // i==3 will be skipped
x=x + "The number is " + i + "<br>";
}

JavaScript HTML DOM


The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

It defines:

● The HTML elements as objects


● The properties of all HTML elements
● The methods to access all HTML elements
● The events for all HTML elements

JavaScript - HTML DOM Methods


A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (add or deleting an HTML element).

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>

getElementById is a method, while innerHTML is a property.

The getElementById Method


The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.
The innerHTML Property
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The HTML DOM Document Object
The document object represents your web page.
If you want to access any element in an HTML page, you always start with accessing the
document object.

Finding HTML Elements

Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Finding HTML Element by Id


Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p id="intro">Finding HTML Elements by Id</p>
<p>This example demonstrates the <b>getElementsById</b> method.</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML = "The text from the intro paragraph is: " +
element.innerHTML;
</script>
</body>
</html>

Output:
Finding HTML Elements by Tag Name
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Tag Name.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: ' +
element[0].innerHTML;
</script>
</body>
</html>

Output:

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<div id="main">
<p>Finding HTML Elements by Tag Name</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
</div>
<p id="demo"></p>
<script>
const x = document.getElementById("main");
const y = x.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 'The first paragraph (index 0) inside "main"
is: ' + y[0].innerHTML;
</script>
</body>
</html>

Output:
Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name,
use getElementsByClassName()

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Class Name.</p>
<p class="intro">Hello World!</p>
<p class="intro">This example demonstrates the <b>getElementsByClassName</b>
method.</p>
<p id="demo"></p>
<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>
</body>
</html>

Output:
Finding HTML Elements by CSS Selectors
To find all HTML elements that match a specified CSS selector (id, class names, types,
attributes, values of attributes, etc), use the querySelectorAll() method.
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Query Selector</p>
<h1 class="intro">Hello World!.</h1>
<p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p>
<p id="demo"></p>
<script>
const x = document.querySelectorAll("h1.intro");
document.getElementById("demo").innerHTML = 'The first paragraph (index 0) with
class="intro" is: ' + x[0].innerHTML;
</script>
</body>
</html>

Output:

JavaScript HTML DOM -Changing HTML


The HTML DOM allows JavaScript to change the content of HTML elements.
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

<p>The paragraph above was changed by a script.</p>


</body>
</html>

Output:

Eg:
<script>
var a=document.getElementById("p1").innerHTML;
console.log(a);
document.getElementById("p1").innerHTML="new text"
</script>

Output:

Changing the Value of an Attribute


Syntax:
document.getElementById(id).attribute = new value

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<img id="image" src="smiley.gif" width="160" height="120">
<script>
document.getElementById("image").src = "landscape.jpg";
</script>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
</body>
</html>

JavaScript HTML DOM Events


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<h2 onclick="this.innerHTML='Ooops!'">Click on this text!</h2>
</body>
</html>

HTML Event Attributes

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>

Output:
Assign Events Using the HTML DOM
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Events</h2>
<p>Click "Try it" to execute the displayDate() function.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick = displayDate;
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>

JavaScript HTML DOM EventListener

The addEventListener() method attaches an event handler to the specified


element.

The addEventListener() method attaches an event handler to an element


without overwriting existing event handlers.

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

</body>
</html>

JavaScript Date Objects

new Date() creates a date object with the current date and time

Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>

Output:

new Date()
new Date(date string)
new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)

Eg:
<script>
const d = new Date("2022-03-25");
document.getElementById("demo").innerHTML = d;
</script>

Output:
Eg:
<script>
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
document.getElementById("demo").innerHTML = d;
</script>

One and two digit years will be interpreted as 19xx


<script>
const d = new Date(99, 11, 24);
document.getElementById("demo").innerHTML = d;
</script>

Displaying Dates
JavaScript will (by default) output dates using the toString() method. This is a string
representation of the date, including the time zone.

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.toString();
</script>

The toDateString() method converts a date to a more readable format

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
</script>

Output:
The toUTCString() method converts a date to a string using the UTC standard

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>

Output:

The toISOString() method converts a date to a string using the ISO standard

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.toISOString();
</script>

Output:

Date Input - Parsing Dates


Date.parse() returns the number of milliseconds between the date and month

Eg:
<p id="demo"></p>
<script>
const msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;
</script>

Output:

JavaScript Get Date Methods


Date Get Methods

Method Description

getFullYear() Get year as a four digit number (yyyy)

getMonth() Get month as a number (0-11)

getDate() Get day as a number (1-31)

getDay() Get weekday as a number (0-6)

getHours() Get hour (0-23)

getMinutes() Get minute (0-59)

getSeconds() Get second (0-59)

getMilliseconds() Get millisecond (0-999)

getTime() Get time (milliseconds since January 1, 1970)

Eg:
<p id="demo"></p>
<script>
const d = new Date("2021-03-25")
document.getElementById("demo").innerHTML = d.getFullYear();
</script>

Eg:
<p id="demo"></p>
<script>
const d = new Date("2021-03-25");
document.getElementById("demo").innerHTML = d.getMonth() + 1;
</script>
Eg:
<p id="demo"></p>
<script>
const d = new Date("2021-03-25");
document.getElementById("demo").innerHTML = d.getMonth() + 1;
</script>

The getTimezoneOffset() Method

The getTimezoneOffset() method returns the difference (in minutes) between local time an UTC
time

Eg:
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getTimezoneOffset();
</script>

JavaScript Set Date Methods


Set Date Methods
Set Date methods are used for setting a part of a date:
Method Description

setDate() Set the day as a number (1-31)

setFullYear() Set the year (optionally month and day)

setHours() Set the hour (0-23)

setMilliseconds() Set the milliseconds (0-999)

setMinutes() Set the minutes (0-59)

setMonth() Set the month (0-11)

setSeconds() Set the seconds (0-59)

setTime() Set the time (milliseconds since January 1, 1970)

Eg:
<p id="demo"></p>
<script>
const d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>

Output:

2. d.setFullYear(2020, 11, 3);

3. d.setMonth(11);

4. d.setDate(15);

5. d.setDate(d.getDate() + 50);

JavaScript RegExp Reference

The RegExp Object


A regular expression is a pattern of characters.
The pattern is used for searching and replacing characters in strings.
The RegExp Object is a regular expression with added Properties and Methods.

Syntax
/pattern/modifier(s);

Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Regular Expression</h1>
<h2>The /i Modifier</h2>
<p>A case-insensitive search for "w3schools" in a string:</p>
<p id="demo"></p>
<script>
let text = "Javascript programming ";
let pattern = /Java/;
let result = text.match(pattern);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>

Output:
Modifiers

Modifier Description

/g Perform a global match (find all)

/i Perform case-insensitive matching

/m Perform multiline matching

Brackets
Brackets are used to find a range of characters

Bracket Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-digit)

(x|y) Find any of the alternatives specified

Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Regular Expression</h1>
<h2>The /i Modifier</h2>
<p>A case-insensitive search for "w3schools" in a string:</p>
<p id="demo"></p>
<script>
function regular() {
let str1 = 'javascript programming';
let strings = /[a-z]/g;
let match4 = str1.match(strings);
console.log('Found ' + match4.length + ' matches: ' + match4);
}
regular();
</script>
</body>
</html>

Output:

The RegExp (x|y) Expression in JavaScript is used to search any of the specified characters
(separated by |).
Eg:
function regular() {
let str1 = "012034567895";
let regex4 = /(0|5)/g;
let match4 = str1.match(regex4);

console.log("Found " + match4.length+ " matches: " + match4);


}
regular();

The RegExp [0-9] Expression in JavaScript is used to search any digit which is between the
brackets. The character inside the brackets can be a single digit or a span of digits.

Eg:
function regular() {
let str1 = "123456790";
let regex4 = /[0-4]/g;
let match4 = str1.match(regex4);

console.log("Found " + match4.length+ " matches: " + match4);


}
regular();

Eg:
function regular() {
let str1 = "128@$%";
let replacement = "#";
let regex4 = new RegExp("[0-9]", "g");
let match4 = str1.replace(regex4, replacement);

console.log(" New string: " + match4);


}
regular();

The RegExp [^0-9] Expression in JavaScript is used to search any digit which is not between
the brackets. The character inside the brackets can be a single digit or a span of digits.

Eg:
function regular()
{
let str1 = "123456790";
let regex4 = /[^0-4]/g;
let match4 = str1.match(regex4);

console.log("Found " + match4.length


+ " matches: " + match4);
}
regular();

Eg:
function regular()
{
let str1 = "128@$%";
let replacement = "#";
let regex4 = new RegExp("[^0-9]", "g");
let match4 = str1.replace(regex4, replacement);
console.log("Found " + match4.length
+ " matches: " + match4);
}
regular();

Metacharacters
Metacharacters are characters with a special meaning:
Character Description

. Find a single character, except newline or line terminator

\w Find a word character

\W Find a non-word character

\d Find a digit

\D Find a non-digit character

\s Find a whitespace character

\S Find a non-whitespace character

\b Find a match at the beginning/end of a word, beginning like this: \bHI, end
like this: HI\b

\B Find a match, but not at the beginning/end of a word

\0 Find a NULL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx


\xdd Find the character specified by a hexadecimal number dd

\udddd Find the Unicode character specified by a hexadecimal number dddd

The RegExp \b Metacharacter in JavaScript is used to find a match at the beginning or end of a
word. If a match is found it returns the word else it returns NULL.

Eg:
function regular() {
let str1 = "javascript@_123_$";
let regex4 = /\java/gi;
let match4 = str1.match(regex4);

console.log("Found " + match4.length + " match: " + match4);


}
regular();

JavaScript Errors

Throw, and Try...Catch...Finally

The try statement defines a code block to run (to try).


The catch statement defines a code block to handle any error.
The finally statement defines a code block to run regardless of the result.
The throw statement defines a custom error.

JavaScript try and catch


The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the
try block.

Syntax:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Error Handling</h2>
<p>How to use <b>catch</b> to display an error.</p>
<p id="demo"></p>
<script>
try {
addlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>

Output:

The throw Statement


The throw statement allows you to create a custom error.
Technically you can throw an exception (throw an error).
The exception can be a JavaScript String, a Number, a Boolean or an Object
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript try catch</h2>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x.trim() == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
The finally Statement
Syntax:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript try catch</h2>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x.trim() == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>

The Error Object


JavaScript has a built in error object that provides error information when an error occurs.
The error object provides two useful properties: name and message.

Property Description

name Sets or returns an error name

message Sets or returns an error message (a string)

Error Name Values


Six different values can be returned by the error name property:
Error Name Description

EvalError An error has occurred in the eval() function

RangeError A number "out of range" has occurred

ReferenceError An illegal reference has occurred


SyntaxError A syntax error has occurred

TypeError A type error has occurred

URIError An error in encodeURI() has occurred

Range Error
A RangeError is thrown if you use a number that is outside the range of legal values.

Eg:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Errors</h1>
<h2>The RangeError</h2>
<p>You cannot set the number of significant digits too high:</p>
<p id="demo">
<script>
let num = 1;
try {
num.toPrecision(500);
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>
</body>
</html>

Reference Error

A ReferenceError is thrown if you use (reference) a variable that has not been declared

Eg:
<script>
let x = 5;
try {
x = y + 1;
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>

Syntax Error

A SyntaxError is thrown if you try to evaluate code with a syntax error

Eg:
<script>
try {
eval("alert('Hello)");
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>

Type Error

A TypeError is thrown if an operand or argument is incompatible with the type expected by an


operator or function.

Eg:
<script>
let num = 1;
try {
num.toUpperCase();
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>

URI (Uniform Resource Identifier) Error

A URIError is thrown if you use illegal characters in a URI function

Eg:
<script>
try {
decodeURI("%%%");
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>

Build_in objects

Date object
Array Object

Properties

An Array object has one property, length.

The length property indicates the number of components in an Array object

Methods

The Array object has three methods:

● join: Joins all elements of an array into a string.


● reverse: Reverses elements of an array
● sort: Sorts elements of an array based on a specified comparison function.

Math Object
The built-in Math object has properties and methods for mathematical constants and functions,
respectively.

Math.PI

Math.sin()

Math.abs(number)

Math.cos(number)

Math.exp(number)

Math.min(number1, number2)

Math.max(number1, number2)

Math.pow(base, exponent)

Math.round(number)

Math.sqrt(number)

Number Object
The Boolean object corresponds to the number primitive type.

Properties

The properties of the Number object are constants.

MAX_VALUE

The largest number representable in JavaScript, 1.7976931348623157e308.

MIN_VALUE

The smallest number representable in JavaScript, 2.2250738585072014e-308.

NaN

The literal NaN, representing a value that is "not a number."

String Object
A String is an object representing a series of characters.

Constructors

A string object is created whenever a string literal is used or assigned to a variable or with the
explicit constructor:

identifierName = new String(stringValue)

stringValue can be a string literal or string-valued variable.

Properties

A String object has one property, length.


length

The length property indicates the total number of characters in a String object. The syntax is:

stringObject.length

Methods

stringName.methodName(parameters)

indexOf

Returns the index within the calling string object of the first occurrence of the specified value,
starting the search at fromIndex.

stringName.indexOf(searchValue)

stringName.indexOf(searchValue, fromIndex)

lastIndexOf

Returns the index within the calling string object of the last occurrence of the specified value.
The calling string is searched backward, starting at fromIndex.

stringName.lastIndexOf(searchValue,)

stringName.lastIndexOf(searchValue, fromIndex)

substring

Returns a subset of a string object.

stringName.substring(indexA, indexB)

charAt

Returns the character at the specified index.

stringName.charAt(index)

toLowerCase

Returns the calling string value converted to lowercase.

stringName.toLowerCase()

toUpperCase

Returns the calling string value converted to uppercase.

stringName.toUpperCase()

stringName is any string.

split

Splits a String object into an array of strings by separating the string into substrings. Returns an
Array object. Syntax:

stringName.split(separator)
Event handling

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

Syntax:

<element event="some JavaScript">

Eg:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>

DHTML JavaScript

DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be
customized or changed according to user inputs i.e. a page that is interactive with the user. In
earlier times, HTML was used to create a static page. It only defined the structure of the content
that was displayed on the page. With the help of CSS, we can beautify the HTML page by
changing various properties like text size, background color, etc.
DHTML included JavaScript along with HTML and CSS to make the page dynamic. This
combo made the web pages dynamic and eliminated the problem of creating static pages for
each user. To integrate JavaScript into HTML, a Document Object Model(DOM) is made for the
HTML document. In DOM, the document is represented as nodes and objects which are
accessed by different languages like JavaScript to manipulate the document.
Eg:
<!Doctype html>
<html>
<body>
<h1 id = "para1" style="display: flex; margin: auto; justify-content: center;"> javascript </h1>
<input type = "Submit" onclick = "Click()" style="display: flex; margin: auto; justify-content:
center;"/>
<script>
function Click() {
document.getElementById("para1").style.color = "green";
window.alert("Color changed to green");
}
</script>
</body>
</html>

JSON

● JSON stands for JavaScript Object Notation


● JSON is a lightweight data-interchange format
● JSON is plain text written in JavaScript object notation
● JSON is used to send data between computers
● JSON is language independent

JSON Syntax

JSON syntax is derived from JavaScript object notation syntax:

● Data is in name/value pairs


● Data is separated by commas
● Curly braces hold objects
● Square brackets hold arrays

JSON Data - A Name and a Value

JSON data is written as name/value pairs (aka key/value pairs).

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by
a value

Eg:

"name":"John"

JSON - Evaluates to JavaScript Objects

The JSON format is almost identical to JavaScript objects.

In JSON, keys must be strings, written with double quotes

In JavaScript, keys can be strings, numbers, or identifier names

Eg:

{"name":"John"}

JSON Values

In JSON, values must be one of the following data types:

● a string
● a number
● an object
● an array
● a boolean
● null

In JSON, string values must be written with double quotes


In JavaScript, you can write string values with double or single quotes

JSON Files

● The file type for JSON files is ".json"


● The MIME type for JSON text is "application/json"

JSON Data Types

In JSON, values must be one of the following data types:

● a string
● a number
● an object (JSON object)
● an array
● a boolean
● null

JSON Strings

Strings in JSON must be written in double quotes.

Eg:

{"name":"John"}

JSON Numbers

Numbers in JSON must be an integer or a floating point.

Eg:

{"age":30}

JSON Objects
JSON object literals are surrounded by curly braces {}.
JSON object literals contains key/value pairs.
Keys and values are separated by a colon.
{"employee":{"name":"John", "age":30, "city":"New York"}}

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON Literal</h2>
<p id="demo"></p>
<script>
const myObj = {"name":"John", "age":30, "car":null};
document.getElementById("demo").innerHTML = myObj.name;
</script>
</body>
</html>

Accessing Object Values


You can access object values by using dot (.) notation
Eg:
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>

You can also access object values by using bracket ([]) notation
Eg:
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj["name"];
</script>

JSON Arrays

Eg:

<!DOCTYPE html>
<html>
<body>
<h2>Creating an Array from a Literal</h2>
<p id="demo"></p>
<script>
const myArray = ["Ford", "BMW", "Fiat"];
document.getElementById("demo").innerHTML = myArray;
</script>
</body>
</html>

Accessing Array Values


You access array values by index
Eg:
<script>
const myJSON = '["Ford", "BMW", "Fiat"]';
const myArray = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myArray[0];
</script>

JSON Booleans

{"sale":true}

JSON null

{"middlename":null}

JSON.parse()
A common use of JSON is to exchange data to/from a web server.
When receiving data from a web server, the data is always a string.
Parse the data with JSON.parse(), and the data becomes a JavaScript object.
JSON.parse()used to convert text into a JavaScript object

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
</body>
</html>

Array as JSON

When using the JSON.parse() on a JSON derived from an array, the method will return a
JavaScript array, instead of a JavaScript object.

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>Parsing a JSON Array.</h2>
<p>Data written as an JSON array will be parsed into a JavaScript array.</p>
<p id="demo"></p>
<script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr[0];
</script>
</body>
</html>

Parsing Dates
Date objects are not allowed in JSON.
If you need to include a date, write it as a string.
You can convert it back into a date object later

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>Convert a string into a date object.</h2>
<p id="demo"></p>
<script>
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
</script>
</body>
</html>

Parsing Functions
Functions are not allowed in JSON.
If you need to include a function, write it as a string.
You can convert it back into a function later

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>Convert a string into a function.</h2>
<p id="demo"></p>
<script>
const text = '{"name":"John", "age":"function() {return 30;}", "city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();
</script>

</body>
</html>

JSON.stringify()
A common use of JSON is to exchange data to/from a web server.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with JSON.stringify().

Eg:
<!DOCTYPE html>
<html>
<body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>

JSON Function Files

A common use of JSON is to read data from a web server, and display the data in a web page.

4 easy steps, how to read JSON data, using function files.

1: Create an array of objects.

2: Create a JavaScript function to display the array.

3: Use an array literal as the argument (instead of the array variable):

4: Put the function in an external js file

myTutorials.js
myFunction([
{"display": "JavaScript Tutorial","url": "https://www.w3schools.com/js/default.asp"},
{"display": "HTML Tutorial","url": "https://www.w3schools.com/html/default.asp"},
{"display": "CSS Tutorial","url": "https://www.w3schools.com/css/default.asp"}]);

Eg:
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var myArray = [
{ "display": "JavaScript Tutorial", "url": "https://www.w3schools.com/js/default.asp" },
{"display": "HTML Tutorial","url": "https://www.w3schools.com/html/default.asp"},
{ "display": "CSS Tutorial", "url": "https://www.w3schools.com/css/default.asp" }
];

myFunction(myArray);
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
</body>
</html>

JSON Http Request


1: Create an array of objects.
2: Create a JavaScript function to display the array.
3: Create a text file
4: Read the text file with an XMLHttpRequest

Eg:
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>

myTutorials.txt
[
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
},
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "jQuery Tutorial",
"url": "https://www.w3schools.com/jquery/default.asp"
},
{
"display": "SQL Tutorial",
"url": "https://www.w3schools.com/sql/default.asp"
},
{
"display": "PHP Tutorial",
"url": "https://www.w3schools.com/php/default.asp"
},
{
"display": "XML Tutorial",
"url": "https://www.w3schools.com/xml/default.asp"
}
]

You might also like