Professional Documents
Culture Documents
Web Technologies
Unit 3
Java Script
13
Add JavaScript Code inside Head Section
• JavaScript code is placed inside the head section of an HTML page
and the function is invoked when a button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>
Add JavaScript Code inside Head Section
</title>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "Content changed!";
}
</script>
</head>
<body>
<h2>
Add JavaScript Code
inside Head Section
</h2>
</html>
Add JavaScript Code inside Body Section
• JavaScript Code is placed inside the body section of an HTML page
and the function is invoked when a button is clicked.
<!DOCTYPE html>
<html>
<head>
<title>
Add JavaScript Code inside Body Section
</title>
</head>
<body>
<h2>
Add JavaScript Code
inside Body Section
</h2>
<script>
function myFun() {
External JavaScript
• JavaScript can also be used in external files. The file extension of the
JavaScript file will be .js.
• To use an external script put the name of the script file in the src
attribute of a script tag. External scripts cannot contain script tags.
<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>
</body>
</html>
JavaScript Example
1.<script>
2.document.write("Hello JavaScript by JavaScript");
3.</script>
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about the
data.
The document.write() function is used to display dynamic content through JavaScript.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint"); }
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
JavaScript Versions
Added:
•Regular Expression
ES3 ECMAScript 3 1999 •try/catch
•Exception Handling
•switch case and do-while
Added:
•JavaScript “strict mode”
ES5 ECMAScript 5 2009
•JSON support
•JS getters and setters
Added:
•let and const
•Class declaration
ES6 ECMAScript 2015 2015
•import and export
•for..of loop
•Arrow functions
Added:
•Block scope for variable
ES7 ECMAScript 2016 2016 •async/await
•Array.includes function
•Exponentiation Operator
Added:
•Object.values
ES8 ECMAScript 2017 2017
•Object.entries
•Object.getOwnPropertiesDescriptors
Added:
ES9 ECMAScript 2018 2018 •spread operator
•rest parameters
Added:
•Array.flat()
ES10 ECMAScript 2019 2019
•Array.flatMap()
•Array.sort is now stable
Added:
ES11 ECMAScript 2020 2020 •BigInt primitive type
•nullish coalescing operator
Added:
ES12 ECMAScript 2021 2021 •String.replaceAll() Method
•Promise.any() Method
Added:
•Top-level await
ES13 ECMAScript 2022 2022
•New class elements
•Static block inside classes
<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>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p id="demo"></p>
<script>
let x = 5;
let y = 6;
let z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p id="demo"></p>
<script>
const price1 = 5;
const price2 = 6;
document.getElementById("demo").innerHTML =
</script>
</body>
</html>
JavaScript Operators and Constructs
<h1>JavaScript Arithmetic</h1>
<h2>The * Operator</h2>
<p id="demo"></p>
<script>
let x = 5;
let y = 2;
let z = x * y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
Assignment Operators
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
document.getElementById("demo").innerHTML = "Is A less than B? " + result;
</script>
</body>
</html>
JavaScript Functions
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b)
{
return a * b;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<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>
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if JavaScript Keywords Marks a block of statements to be executed on a
JavaScript statements condition
often start with
switch
a keyword to identify Marks a block of statements to be executed in
the JavaScript action to different cases
for be performed. Marks a block of statements to be executed in a
loop
function Declares a function
return Exits a function
try Implements error handling to a block of
statements
Sr.No. Statement Description
1. switch case A block of statements in which execution of code depends upon different cases.
The interpreter checks each case against the value of the expression until a match
is found. If nothing matches, a default condition will be used.
2. If else The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.
3. While The purpose of a while loop is to execute a statement or code block repeatedly as
long as expression is true. Once expression becomes false, the loop will be exited.
4. do while Block of statements that are executed at least once and continues to be executed
while condition is true.
5. for Same as while but initialization, condition and increment/decrement is done in the
same line.
7. continue The continue statement tells the interpreter to immediately start the next iteration
of the loop and skip remaining code block.
8. break The break statement is used to exit a loop early, breaking out of the enclosing
curly braces.
9. function A function is a group of reusable code which can be called anywhere in your
programme. The keyword function is used to declare a function.
13. catch A block of statements that are executed when an error occur.
</body>
</html>
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
A JavaScript program is a list of programming statements.
JavaScript statements are the commands to tell the browser to what action to perform. Statements are
separated by semicolon (;).
In HTML, JavaScript programs are executed by the web browser.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>
<p id="demo"></p>
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("demo").innerHTML ="The value of z is " + z + ".";
</script>
</body>
</html>
Output of this statement is given on the next slide
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
Example:-
<!DOCTYPE html>
<html>
<body
<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p><script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
</script>
</body>
</html>
JavaScript Arrays
• An array is a special variable, which can hold more than one
value:
const cars = ["Saab", "Volvo", "BMW"];
• If you have a list of items (a list of car names, for example),
storing the cars in single variables could look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
JavaScript has arrays that are indexed starting at 0
•
• Using an array literal is the easiest way to create a
JavaScript Array.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<p id="demo"></p>
<script>
const cars = [
"Saab",
"Volvo",
"BMW"
];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
JavaScript Objects
In JavaScript, Objects can be created using two different
methodologies namely Literal Form and Constructed Form.
•Literal Form: The literal form uses the construction of object
literals that can be said as a collection of key-value pairs enclosed
within a pair of curly braces. The syntaxial form is shown below.
let obj = { key1: value1,
key2: value2, ... };
•Constructed Form: The Constructed form uses either an object constructor function or the new
keyword to create an empty object ad then adds properties to the object one by one. The syntaxial
forms are shown below.
•Object Constructor Function: In this methodology, the user creates an explicit function to take
required values as parameters and assign them as the properties of the desired object.
function
obj(value1, value2, ...) {
this.key1 = value1;
this.key2 = value2; ... }
•Using New Keyword: This methodology uses the New keyword in front of any constructor method or
any built-in constructor method ( such as Object, Date, String, etc) and creates a new instance of the
following object by mounting it on memory.
let obj = new Object();
obj.key1 = value1;
obj.key2 = value2; ...
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
</body>
</html>
Java Script Documents
• The HTML DOM document object is the owner of all other objects in
your web page. The document object represents the whole html
document.
• If you want to access any element in an HTML page, you always start
with accessing the document object.
• When html document is loaded in the browser, it becomes a
document object.
• It is the root element that represents the html document. It has
properties and methods.
• By the help of document object, we can add dynamic content to our
web page.
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
Javascript - document.getElementById() method
<!DOCTYPE html>
<html>
<body>
<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>
Javascript - document.getElementsByTagName() method
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");
</script>
</body>
</html>
Javascript - document.getElementsByClass Name()
method
<!DOCTYPE html>
<html>
<body>
<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>
Changing HTML Elements
Property Description
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
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
Adding Events Handlers
Method Description
document.getElementById(id).onclick Adding event handler
= function(){code} code to an onclick event
Finding HTML Objects
document.applets Deprecated 1
document.domConfig Obsolete. 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
• Form name tag is used to define the name of the form. The name of the form here is "Login_form". This name
will be referenced in the JavaScript form.
• The action tag defines the action, and the browser will take to tackle the form when it is submitted. Here, we
have taken no action.
• The method to take action can be either post or get, which is used when the form is to be submitted to the
server. Both types of methods have their own properties and rules.
• The input type tag defines the type of inputs we want to create in our form. Here, we have used input type as
'text', which means we will input values as text in the textbox.
• Net, we have taken input type as 'password' and the input value will be password.
• Next, we have taken input type as 'button' where on clicking, we get the value of the form and get displayed.
• Referencing forms
• Now, we have created the form element using HTML, but we also need to make its connectivity to JavaScript.
For this, we use the getElementById () method that references the html form element to the JavaScript code.
• The syntax is as follows:
let form = document.getElementById('subscribe');
1.<html>
2.<head>
3.<title> Login Form</title>
4.</head>
5.<body>
6.<h3> LOGIN </h3>
7.<formform ="Login_form" onsubmit="submit_form()">
8.<h4> USERNAME</h4>
9.<input type="text" placeholder="Enter your email id"/>
10.<h4> PASSWORD</h4>
11.<input type="password" placeholder="Enter your password"/></br></br>
12.<input type="submit" value="Login“ onclick=“submit_form()”/>
13.<input type="button" value="SignUp" onClick="create()"/>
14.</form>
15.<script type="text/javascript">
16.function submit_form(){
17.alert("Login successfully");
18.}
19.function create(){
20.window.location="signup.html";
21.}
22.</script>
23.</body>
24.</html>
Inner HTML
When you use innerHTML, you can change the page's content without refreshing the page.
<script>
This can make your website feel quicker and more responsive to user input.
The innerHTML property can be used along with getElementById() within your JavaScript code
to refer to an HTML element and change its contents.
<script>
function Msg1(){
document.getElementById('myText').innerHTML = 'Hey <strong>Thanks!</strong>';
}
function Msg2(){
document.getElementById('myText').innerHTML = 'Try <strong>message 1</strong>
again...';
}
</script>
<input type="button" onclick="Msg1()" value="Show Message 1">
<input type="button" onclick="Msg2()" value="Show Message 2">
<p id="myText"></p>
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
AJAX - Server Response
document.getElementById("demo").innerHTML = this.respon
seText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
The "ajax_info.txt" file used in the example above, is a
simple text file and looks like this
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers
from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And
XML.</p>
Advantages:
20.79
What is an IP Address?
• An IP address is a string of numbers separated by periods.
• IP addresses are expressed as a set of four numbers — an
example address might be 192.158.1.38.
• Each number in the set can range from 0 to 255. So, the full IP
addressing range goes from 0.0.0.0 to 255.255.255.255.
Types of IP Address
1. IPv4: Internet Protocol version 4.
• It consists of 4 numbers separated by the dots. Each number can be from 0-255 in
decimal numbers. But computers do not understand decimal numbers, they instead
change them to binary numbers which are only 0 and 1.
• Therefore, in binary, this (0-255) range can be written as (00000000 – 11111111).
Since each number N can be represented by a group of 8-digit binary digits. So, a
whole IPv4 binary address can be represented by 32-bits of binary digits.
• In IPv4, a unique sequence of bits is assigned to a computer, so a total of (2^32)
devices approximately = 4,294,967,296 can be assigned with IPv4.
• IPv4 can be written as:
189.123.123.90
Features of IPV4
• An IPv4 address is a 32-bit address that uniquely and universally defines
the connection of a device (for example, a computer or a router) to the
Internet.
• It is a connectionless protocol.
• It utilizes less memory and the addresses can be remembered easily with
the class based addressing scheme.
• It also offers video conferencing and libraries.
• The address space of IPv4 is 232 or 4,294,967,296.
Position of IPv4 in TCP/IP protocol suite
20.83
• The packet transmitted by the sending computer may pass through several LANs
or WANs before reaching the destination computer.
• For this level of communication, we need a global addressing scheme; we called
this logical addressing
• we use the term IP address to mean a logical address in the network layer of the
TCP/IP protocol suite.
• The Internet addresses are 32 bits in length; this gives us a maximum of 2 32
addresses. These addresses are referred to as IPv4 (IP version 4) addresses or
simply IP addresses if there is no confusion.
IPv4 datagram format
20.85
The IPV4 Protocol
The IPv4 (Internet Protocol) header consists of:
• Version: which version of the protocol
• IHL: how long the header is.(5-15)
• Type of service: reliability/speed. (6-bit= 3bit precedence + 3
flags D, T, R (delay, throughput, reliability)) (ignored)
• Total length: header + data (max 65535 bytes)
• Identification: to determine which datagram a newly arrived
fragment belongs to.
• DF: don’t fragment (destination is unable to reassemble)
• MF: More fragment and all except the last one have this bit
set.
The IPV4 Protocol
The IPv4 (Internet Protocol) header consists of:
• Fragment offset: tells where in the datagram this fragment
belongs. (multiple of 8 bytes)(13 bits so max 8192 fragments
per datagram)
• Time to live: counter used to limit packet lifetime.(max 255s)
• Protocol: to which transport process to give it to.( TCP/UDP)
• Checksum: verifies the header only.
• Options: to include information not present in the original
design.
The total length field defines the total length of the datagram
including the header.
20.88
IPV4 Addresses
IP address formats.
Dotted-decimal notation and binary notation for an IPv4 address
Example
Solution
We replace each decimal number with its binary
equivalent.
Example
Solution
a. There must be no leading zero (045).
b. There can be no more than four numbers.
c. Each number needs to be less than or equal to 255.
d. A mixture of binary notation and dotted-decimal
notation is not allowed.
Note
The address class can be determined using the following table. For example, IP address 172.31.1.2 has a
first octet of 172, which falls between
128 and 191, so 172.31.1.2 is a Class B address.
Determining the Address Class
Class First octet High-order bits
A 1 - 126 0
B 128 - 191 10
C 192 - 223 110
D 224 - 239 1110
E 240 - 254 1111
An ip address is divided into two parts:
•Network ID: It represents the number of networks.
•Host ID: It represents the number of hosts.
Class A
In Class A, an IP address is assigned to those networks that contain a large number of hosts.M
376
•The network ID is 8 bits long.ay
•The host ID is 24 bits long.
In Class A, the first bit in higher order bits of the first octet is always set to 0 and the remaining
7 bits determine the network ID. The 24 bits determine the host ID in any network.
The total number of networks in Class A = 27 = 128 network address
The total number of hosts in Class A = 224 - 2 = 16,777,214 host address
Class B
In Class B, an IP address is assigned to those networks that range from small-sized to large-sized networks.
•The Network ID is 16 bits long.
•The Host ID is 16 bits long.
In Class B, the higher order bits of the first octet is always set to 10, and the remaining
14 bits determine the network ID. The other 16 bits determine the Host ID.
The total number of networks in Class B = 214 = 16384 network address
The total number of hosts in Class B = 216 - 2 = 65534 host address
Class C
In Class C, an IP address is assigned to only small-sized networks.
•The Network ID is 24 bits long.
•The host ID is 8 bits long.
In Class C, the higher order bits of the first octet is always set to 110, and the remaining
21 bits determine the network ID. The 8 bits of the host ID determine the host in a network.
The total number of networks = 221 = 2097152 network address
The total number of hosts = 28 - 2 = 254 host address
Class D
In Class D, an IP address is reserved for multicast addresses. It does not possess subnetting.
The higher order bits of the first octet is always set to 1110, and the remaining bits determine the host
ID in any network.
Class E
In Class E, an IP address is used for future use or for research and development purposes.
It does not possess any subnetting.
The higher-order bits of the first octet is always set to 1111, and the remaining bits determine
the host ID in any network.
Rules for assigning Host ID:
The Host ID is used to determine the host within any network. The Host ID is assigned based on the following
rules:
•The Host ID must be unique within any network.
•The Host ID in which all the bits are set to 0 cannot be assigned as it is used to represent the network ID of the
IP address.
•The Host ID in which all the bits are set to 1 cannot be assigned as it is reserved for the multicast address.
IP Address Classes
Class Format Purpose Address range Max hosts
A N.H.H.H A few large 1.0.0.0 - 126.0.0.0 16,777,214
organisations
Solution
a. The first bit is 0. This is a class A address.
b. The first 2 bits are 1; the third bit is 0. This is a class C
address.
c. The first byte is 14; the class is A.
d. The first byte is 252; the class is E.
IPv4 (disadvantages)
19.106
InetAddress Class in Networking
Method Description
public static InetAddress getLocalHost() throws This method returns the instance of InetAddress containing the
UnknownHostException local hostname and address.
public static InetAddress getByName( String host ) throws This method returns the instance of InetAddress containing IP
UnknownHostException and Host name of host represented by host argument.
public static InetAddress[] getAllByName( String hostName This method returns the array of the instance of InetAddress
) throws UnknownHostException class which contains IP addresses.
public static InetAddress getByAddress( byte IPAddress[] This method returns an InetAddress object created from the raw
) throws UnknownHostException IP address.
public static InetAddress getByAddress( String hostName, byte This method creates and returns an InetAddress based on the
IPAddress[] ) throws UnknownHostException provided hostname and IP address.
InetAddress — Instance Methods
• InetAddress class has plenty of instance methods that can be called using the object. The instance methods are
–
Method Description
equals(Object obj) This function compares this object against the specified object.
getAddress() This method returns the raw IP address of this InetAddress object, in bytes.
getCanonicalHostName() This method returns the fully qualified domain name for this IP address.
getHostName() This method returns the host name for this IP address.
isAnyLocalAddress() This method utility routine to check if the InetAddress is an unpredictable address.
isLinkLocalAddress() This method utility routine to check if the address is not linked to local unicast address.
isLoopbackAddress() This method used to check if the InetAddress represents a loopback address.
This method utility routine check if this address has a multicast address of
isMCGlobal()
global scope.
This method utility routine check if this address has a multicast address of
isMCLinkLocal()
link-local scope.
isMCNodeLocal() This method utility routine check if the multicast address has node scope.
This method utility routine check if the multicast address has an organization
isMCOrgLocal()
scope.
isMCSiteLocal() This method utility routine check if the multicast address has site scope.
Packet Switching in Computer Networks
• Packet Switching is a technique of switching in which the
message is usually divided into smaller pieces that are known
as packets.