Unit 2
Unit 2
Javascript:
JavaScript is the scripting language of the Web.
JavaScript is the world's most popular programming language.
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
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:
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
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.
Eg:
let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
// 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");
Eg:
let x = 16 + "Volvo";
//16Volvo
let x = "Volvo" + 16 + 4;
// Volvo164
the first operand is a string, all operands are treated as strings.
// Without decimals:
let x2 = 34;
Exponential Notation
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
Javascript numbers are always one type: double (64-bit floating point).
JavaScript Booleans
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");
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>
Eg:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
//4
//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";
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.
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
Empty Values
An empty value has nothing to do with undefined.
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:
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
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
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;
}
Example
If the day is NOT Saturday or Sunday, then write a default message:
JavaScript Loops
Different Kinds of Loops
JavaScript supports different kinds of loops:
● for - loops through a block of code a number of times
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>
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.
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
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>";
}
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:
It defines:
Eg:
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
Method Description
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:
Output:
Eg:
<script>
var a=document.getElementById("p1").innerHTML;
console.log(a);
document.getElementById("p1").innerHTML="new text"
</script>
Output:
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>
<!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>
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>
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>
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>
<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:
Eg:
<p id="demo"></p>
<script>
const msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;
</script>
Output:
Method Description
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 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>
Eg:
<p id="demo"></p>
<script>
const d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>
Output:
3. d.setMonth(11);
4. d.setDate(15);
5. d.setDate(d.getDate() + 50);
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
Brackets
Brackets are used to find a range of characters
Bracket Description
[^0-9] Find any character NOT between the brackets (any non-digit)
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);
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);
Eg:
function regular() {
let str1 = "128@$%";
let replacement = "#";
let regex4 = new RegExp("[0-9]", "g");
let match4 = str1.replace(regex4, replacement);
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);
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
\d Find a digit
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end
like this: HI\b
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);
JavaScript Errors
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:
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>
Property Description
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
Eg:
<script>
try {
eval("alert('Hello)");
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>
Type Error
Eg:
<script>
let num = 1;
try {
num.toUpperCase();
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>
Eg:
<script>
try {
decodeURI("%%%");
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>
Build_in objects
Date object
Array Object
Properties
Methods
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
MAX_VALUE
MIN_VALUE
NaN
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:
Properties
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
stringName.substring(indexA, indexB)
charAt
stringName.charAt(index)
toLowerCase
stringName.toLowerCase()
toUpperCase
stringName.toUpperCase()
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
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:
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 Syntax
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by
a value
Eg:
"name":"John"
Eg:
{"name":"John"}
JSON Values
● a string
● a number
● an object
● an array
● a boolean
● null
JSON Files
● a string
● a number
● an object (JSON object)
● an array
● a boolean
● null
JSON Strings
Eg:
{"name":"John"}
JSON Numbers
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>
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>
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>
A common use of JSON is to read data from a web server, and display the data in a web page.
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>
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"
}
]