Unit II - WT
Unit II - WT
Contents of Unit II
JavaScript: Introduction to JavaScript, JavaScript in
perspective, basic syntax, variables and data types,
statements, operators, literals, functions, objects, arrays,
built in objects, JavaScript debuggers.
DOM: Introduction to Document Object Model, DOM
history and levels, intrinsic event handling, modifying
element style, the document tree, DOM event handling,
jQuery, Overview of Angular JS.
1
Introduction to JavaScript
1. JavaScript is a lightweight, cross-platform, single-
threaded, and interpreted compiled programming
language which is also known as the scripting
language for webpages.
2. It is well-known for the development of web pages,
and many non-browser environments also use it.
3. JavaScript is a weakly typed language (dynamically
typed).
3
2
Java Script
Dynamic
5
Client-side:
It supplies objects to control a browser and its Document
3
Server-side:
• It supplies objects relevant to running JavaScript on a
server. For if the server-side extensions allow an
application to communicate with a database, and
provide continuity of information from one invocation
to another of the application or perform file
manipulations on a server.
• The useful framework which is the most famous these
days is node.js.
7
Imperative language –
• In imperative programming, your code is based on
statements that change the program state by telling
the computer how to do things.
• In other words, your code is based on defining
variables and changing the values of those variables.
• It simply controls the flow of computation.
4
Declarative programming –
In declarative programming, your code is based
on expressions that evaluate their result based
on their input by telling the computer what you
want.
10
5
JavaScript can be added to your HTML file in two ways:
Internal JS: We can add JavaScript directly to our HTML
file by writing the code inside the <script> tag. The
<script> tag can either be placed inside the <head> or the
<body> tag according to the requirement.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Basic Example to Describe JavaScript
</title>
</head>
<body>
<!-- JavaScript code can be embedded inside
head section or body section -->
<script>
console.log("Welcome to JavaScript World");
</script>
</body>
</html>
JavaScript World
12
6
History of JavaScript:
• It was created in 1995 by Brendan Eich while he was an
engineer at Netscape.
• It was originally going to be named LiveScript but was renamed.
• Unlike most programming languages, JavaScript language has no
concept of input or output.
• It is designed to run as a scripting language in a host
environment, and it is up to the host environment to provide
mechanisms for communicating with the outside world.
• The most common host environment is the browser.
13
Features of JavaScript:
• JavaScript is the most popular language on earth.
• With advances in browser technology and JavaScript
having moved into the server with Node.js and other
frameworks, JavaScript is capable of so much more.
Here are a few things that we can do with JavaScript:
• JavaScript was created in the first place for DOM
manipulation. Earlier websites were mostly static, after
JS was created dynamic Web sites were made.
14
7
• Functions in JS are objects. They may have properties
and methods just like other objects. They can be
passed as arguments in other functions.
• Can handle date and time.
• Performs Form Validation although the forms are
created using HTML.
• No compiler is needed.
15
Applications of JavaScript:
Web Development: Adding interactivity and behavior to static sites
JavaScript was invented to do this in 1995. By using AngularJS that can be
achieved so easily.
Web Applications: With technology, browsers have improved to the extent
that a language was required to create robust web applications. When we
explore a map in Google Maps then we only need to click and drag the
mouse. All detailed view is just a click away, and this is possible only
because of JavaScript. It uses Application Programming Interfaces(APIs)
that provide extra power to the code. The Electron and React are helpful in
this department.
Server Applications: With the help of Node.js, JavaScript made its way
from client to server and Node.js is the most powerful on the server side.
16
8
Games: Not only in websites, but JavaScript also helps in creating games for
Art: Artists and designers can create whatever they want using JavaScript
to draw on HTML 5 canvas, and make the sound more effective also can be
17
18
9
JavaScript Advantages
Changing an image
Implementing
on moving mouse over
form validation
it
Performing complex
React to user actions, calculations
19
JavaScript Advantages
Simple − JavaScript is simple to comprehend and pick up. Both users and
dynamic content.
10
JavaScript Advantages
Server Load − Data validation can be done within the browser itself
rather than being forwarded to the server because JavaScript is client-
side. The entire website does not need to be reloaded in the event of
any discrepancy. Only the chosen area of the page is updated by the
browser.
Interoperability − Because JavaScript seamlessly integrates with other
programming languages, many developers favour using it to create a
variety of applications. Any webpage or the script of another
programming language can contain it.
21
JavaScript Disadvantages
Cannot Debug − Although some HTML editors allow for
debugging, they are not as effective as editors for C or C++.
Additionally, the developer has a difficult time figuring out the
issue because the browser doesn't display any errors.
Unexpected stop of rendering − The website's entire
JavaScript code can stop rendering due to a single error in the
code. It appears to the user as though JavaScript is absent.
The browsers, however, are very forgiving of these mistakes.
22
11
JavaScript Disadvantages
Client-side Security − The user can see the JavaScript code; it could be misused by
others. These actions might involve using the source code anonymously. Additionally,
it is very simple to insert code into the website that impair the security of data
transmitted via the website.
Inheritance − JavaScript does not support multiple inheritance; only one inheritance is
supported. This property of object-oriented languages might be necessary for some
programs.
Browser Support − Depending on the browser, JavaScript is interpreted differently.
Therefore, before publication, the code needs to run on various platforms. We also
need to check the older browsers because some new functions are not supported by
them.
23
Limitations of JavaScript:
Security risks:
JavaScript can be used to fetch data using AJAX or by manipulating tags that
load data such as <img>, <object>, <script>. These attacks are called cross-site
script attacks. They inject JS that is not part of the site into the visitor’s
browser thus fetching the details.
Performance:
JavaScript does not provide the same level of performance as offered by
many traditional languages as a complex program written in JavaScript would
be comparatively slow. But as JavaScript is used to perform simple tasks in a
browser, so performance is not considered a big restriction in its use.
24
12
Complexity:
To master a scripting language, programmers must have a
thorough knowledge of all the programming concepts, core
language objects, and client and server-side objects otherwise it
would be difficult for them to write advanced scripts using
JavaScript.
Weak error handling and type checking facilities:
It is a weakly typed language as there is no need to specify the
data type of the variable. So wrong type checking is not
performed by compile.
25
26
13
What JavaScript Can’t Do?
Basic Syntax
<script>
// JavaScript Code
</script>
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML
(and XHTML, its successor) have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the
scripting language in use and its value should be set to "text/javascript".
28
14
Your First JavaScript Code
<html>
<body>
<script language = "javascript" type = "text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
This code will produce the following result −
Hello World!
29
30
15
Syntax of Javascript
Write JavaScript code inside HTML
Head Tag, Body Tag or External File
Example:
<script >
JavaScript code
</script>
31
32
16
Java Script Example- 2
Print Hello Message
<html>
Script Code in HTML
<head>
file in Head Tag
<script>
document.write("Hello World")
</script>
</head>
</html>
33
34
17
Java Script Example- 4 Print Hello
Message
<html>
<head>
<script> Print Message after
function sayHello() clicking button
{
alert("Hello World")
}
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
35
36
18
• Example using var
var x = 5;
var y = 6;
var z = x + y;
19
• When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed
(Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.
39
JavaScript Identifiers
• All JavaScript variables must be identified with
unique names.
40
20
The general rules for constructing names for variables
(unique identifiers) are:
41
42
21
JavaScript Arithmetic
• As with algebra, you can do arithmetic with JavaScript
variables, using operators like = and +:
Example
let x = 5 + 2 + 3;
• You can also add strings, but strings will be
concatenated:
Example
let x = "John" + " " + "Doe";
• If you put a number in quotes, the rest of the numbers
will be treated as strings, and concatenated.
Example
• let x = 2 + 3 + "5";
43
Example
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
44
22
JavaScript Underscore (_)
• Since JavaScript treats underscore as a letter,
identifiers containing _ are valid variable names:
Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;
45
23
JavaScript Strings
A string (or a text string) is a series of characters like "John
Doe".
Strings are written with quotes.
You can use single or double quotes:
Example
// Using double quotes:
let carName1 = "Volvo XC60";
JavaScript Numbers
All JavaScript numbers are stored as decimal numbers
(floating point).
Numbers can be written with, or without decimals:
Example
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;
48
24
Exponential Notation
• Extra large or extra small numbers can be written
with scientific (exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
49
JavaScript BigInt
• All JavaScript numbers are stored in a a 64-bit
floating-point format.
• JavaScript BigInt is a new datatype (ES2020)
that can be used to store integer values that
are too big to be represented by a normal
JavaScript Number.
Example
let x = BigInt("123456789012345678901234567890");
25
JavaScript Booleans
Booleans can only have two values: true or false.
Example :
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
51
JavaScript Arrays
• JavaScript arrays are written with square brackets.
• Array items are separated by commas.
• The following code declares (creates) an array called
cars, containing three items (car names):
Example
const cars = ["Saab", "Volvo", "BMW"];
52
26
JavaScript Objects
• JavaScript objects are written with curly braces {}.
• Object properties are written as name:value pairs,
separated by commas.
Example :
const person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};
53
Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string“
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
54
27
Undefined
In JavaScript, a variable without a value, has the value
undefined. The type is also undefined.
Example
let car; // Value is undefined
Any variable can be emptied, by setting the value to
undefined. The type will also be undefined.
car = undefined; // 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.
Example
let car = ""; // The value is "", the typeof is
"string"
56
28
Statements
• The programming instructions written in a program in
a programming language are known as statements.
• A JavaScript program is a list of programming
statements.
• In HTML, JavaScript programs are executed by the web
browser.
• The statements are executed, one by one, in the same
order as they are written.
57
Example
document.getElementById("demo").innerHTM
L = "Hello Dolly.";
29
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
Examples
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
When separated by semicolons, multiple statements on one
line are allowed:
a = 5; b = 6; c = a + b;
59
30
JavaScript Line Length and Line Breaks
• Javascript code preferred line length by most
programmers is upto 80 characters.
• If a JavaScript statement does not fit on one line, the
best place to break it is after an operator.
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
61
62
31
JavaScript Keywords
• Keywords are reserved words and cannot be used as variable
name.
• A Javascript keyword tells about what kind of operation it will
perform.
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
JavaScript Operators
64
32
JavaScript Assignment
JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:
Assignment Examples
let x = 10;
JavaScript Addition
The Addition Operator (+) adds numbers:
Adding
let x = 5;
let y = 2;
let z = x + y;
JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;
65
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators
66
33
JavaScript Arithmetic Operators
Arithmetic Operators are used to perform arithmetic on
numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
67
34
JavaScript Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
69
35
The += assignment operator can also be used to add (concatenate) strings:
Example
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be:
What a very nice day
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string
will return a string:
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
The result of x, y, and z will be:
10
55
Hello5 71
72
36
JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit
number. The result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0001 0100 4
<< left shift 5 << 1 0101 << 1 1010 10
>> right shift 5 >> 1 0101 >> 1 0010 2
>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010 2
Literals
JavaScript Literals are the fixed value that
cannot be changed,
you do not need to specify any type of
keyword to write literals.
Literals are often used to initialize variables in
programming
74
37
JavaScript supports various types of literals
which are listed below:
Numeric(Integer) Literal
Floating-Point Literal
Boolean Literal
String Literal
Array Literal
Regular Expression Literal
Object Literal
75
Integer Literals
• It can be expressed in the decimal(base 10),
hexadecimal(base 16) or octal(base 8) format.
• Decimal numeric literals consist of a sequence of digits
(0-9) without a leading 0(zero).
• Hexadecimal numeric literals include digits(0-9), letters
(a-f) or (A-F).
• Octal numeric literals include digits (0-7). A leading
0(zero) in a numeric literal indicates octal format.
120 // decimal literal
021434 // octal literal
0x4567 // hexadecimal literal
76
38
2. Floating Number Literals
It contains a decimal point(.)
A fraction is a floating-point literal
It may contain an Exponent.
77
3. String Literals
A string literal is a combination of zero or
more characters enclosed within a single(') or
double quotation marks (").
"Study" // String literal
'tonight' // String literal
78
39
4. Boolean Literals
Boolean literal supports two values only either
true or false.
79
4. Array Literals
• An array literal is a list of zero or more expressions
representing array elements that are enclosed in a
square bracket([]).
• Whenever you create an array using an array literal,
it is initialized with the elements specified in the
square bracket.
var emp = ["aman","anu","charita"]; // Array literal
80
40
6. Object Literals
• It is a collection of key-value pairs enclosed in curly
braces({}).
• The key-value pair is separated by a comma.
41
FUNCTIONS
Anonymous Function
Named Function
Function with return statement
83
Anonymous Function
<script>
var showMessage = function (){
alert("Hello World!");
};
showMessage();
</script>
84
42
Named Function without argument
function SayHello() {
alert("Hello ");
}
SayHello();
85
86
43
Function with return statement
function sum(val1, val2)
{
return val1 + val2;
};
var result = sum(10,20);
87
44
Objects
• Objects are variables too. But objects can contain
many values.
const car = {type:"Fiat", model:"500", color:"white"};
• The values are written as name:value pairs (name
and value separated by a colon).
• It is a common practice to declare objects with the
const keyword.
89
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span
multiple lines:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
90
45
Object Properties
The name:values pairs in JavaScript objects are called
properties:
91
Examples :
Example1
person.lastName;
Example2
person["lastName"];
92
46
Arrays
• An array is a special variable, which can hold more than one value:
const cars = ["Saab", "Volvo", "BMW"];
Why Use Arrays?
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";
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Creating an Array
• Using an array literal is the easiest way to create a JavaScript Array.
• It is a common practice to declare arrays with the const keyword.
Syntax:
const array_name = [item1, item2, ...];
Example :
const cars = ["Saab", "Volvo", "BMW"];
• Spaces and line breaks are not important. A declaration can span
multiple lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];
47
Built in Objects
• Built-in objects, also known as global objects, are
objects that are readily available in JavaScript
without the need for explicit instantiation.
• They provide a range of functionalities and can be
used directly in your code.
• some commonly used built-in objects in
JavaScript:
95
48
String: Used for manipulating and working with textual
data.
const message = "Hello, World!";
Number: Represents numeric data and provides
various utility methods for mathematical operations.
const pi = 3.14159;
Boolean: Represents a boolean value (true or false).
const isActive = true;
97
49
JSON: Provides methods for working with JSON (JavaScript Object
Notation) data.
const jsonData = '{"name": "Alice", "age": 25}';
const parsedData = JSON.parse(jsonData);
50
JavaScript Debuggers
The debugger keyword stops the execution of JavaScript,
and calls (if available) the debugging function.
This has the same function as setting a breakpoint in the
debugger.
If no debugging is available, the debugger statement has
no effect.
With the debugger turned on, this code will stop
executing before it executes the third line.
101
JavaScript Debuggers
All modern browsers have a built-in JavaScript debugger.
Built-in debuggers can be turned on and off, forcing
errors to be reported to the user.
With a debugger, you can also set breakpoints (places
where code execution can be stopped), and
examine variables while the code is executing.
You activate debugging in your browser with the F12 key,
and select "Console" in the debugger
menu.
102
51
Major Browsers' Debugging Tools
Normally, you activate Firefox
debugging in your browser with Open the browser.
F12, and select "Console" in the From the menu, select "Web
debugger menu.
Otherwise follow these steps: Developer".
Chrome Finally, select "Web Console".
Open the browser. Edge
From the menu, select "More Open the browser.
tools". From the menu, select
From tools, choose "Developer "Developer Tools".
tools". Finally, select "Console".
Finally, select Console. When the new option
"Develop" appears in the menu:
Choose "Show Error Console".
52
DOM: Introduction to Document
Object Model
The Document Object Model (DOM) is a programming
interface for HTML(HyperText Markup Language) and
XML(Extensible markup language) documents.
It defines the logical structure of documents and the way
a document is accessed and manipulated.
DOM is a way to represent the webpage in a structured
hierarchical way so that it will become easier for
programmers and users to glide through the document.
105
53
DOM- Uses
With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
1. JavaScript can change all the HTML elements in the page
2. JavaScript can change all the HTML attributes in the page
3. JavaScript can change all the CSS styles in the page
4. JavaScript can remove existing HTML elements and
attributes
5. JavaScript can add new HTML elements and attributes
107
54
Structure of DOM:
• DOM can be thought of as a Tree or Forest(more than one tree).
• The term structure model is sometimes used to describe the tree-
like representation of a document.
• Each branch of the tree ends in a node, and each node contains
objects.
• Event listeners can be added to nodes and triggered on an
occurrence of a given event.
• One important property of DOM structure models is structural
isomorphism: if any two DOM implementations are used to create a
representation of the same document, they will create the same
structure model, with precisely the same objects and relationships.
109
Tree Structure
110
55
Example
• <html>
• <head>
• <title> My Text </title>
• </head>
• <body>
• <h1> My Header </h1>
• <p> My Paragraph </p>
• </body>
• </html>
111
DOM Levels
112
56
DOM- Properties & Methods
Methods Description
113
Methods Example
.innerHTML document.getElementById(“demo”).inner
HTML
..Value document.getElementById(“t1”).Value
114
57
Example getElementById
<html>
<head><script>
function f1() {
var a= document.getElementById("t1").value;
alert(a); }
</script></head>
<body>
<input type="text" id="t1" >
<input type=button value="click" onclick="f1()">
</body>
</html>
Examples: getElementsByTagName
<html>
<head><script>
function f1() {
document.getElementsByTagName("p")[0].innerHTML="HT
ML"; }
</script></head>
<body>
<p> Hello</p>
<p > How Are You </p>
<input type=button value="click" onclick="f1()">
</body>
</html>
58
Example to calculate length
<script>
function f1() {
alert(document.getElementsByTagName("p").leng
th); }
</script><body>
<p> Hello</p>
<p class= “a1”> How Are You </p>
<h1 class= “a1”>Good Day </h1>
<input type=button value="click" onclick="f1()">
</body>
117
59
Examples:To Disable/Enable element
<script>
function f1() {
document.getElementsById("t1").disabled= true; }
</script>
<body>
<input type="text" id="t1" >
<input type=button value="click" onclick="f1()">
</body>
119
120
60
Properties of DOM:
• Let’s see the properties of the document object that can be
accessed and modified by the document object.
121
Window Object:
Window Object is object of the browser which is always at top of the
hierarchy.
It is like an API that is used to set and access all the properties and
Document object:
When an HTML document is loaded into a window, it becomes a
document object.
122
61
Document object: (Cont..)
The ‘document’ object has various properties that refer to other objects
which allow access to and modification of the content of the web page.
Form Control Elements:: Form can have many control elements such as text
fields, buttons, radio buttons, checkboxes, etc.
123
62
What DOM is not?
• The Document Object Model is not a binary description where it
does not define any binary source code in its interfaces.
• The Document Object Model is not used to describe objects in XML
or HTML whereas the DOM describes XML and HTML documents as
objects.
• The Document Object Model is not represented by a set of data
structures; it is an interface that specifies object representation.
• The Document Object Model does not show the criticality of objects
in documents i.e it doesn’t have information about which object in
the document is appropriate to the context and which is
not.
125
63
// Fetch the value of input with id val2
const num2 =
Number(document.getElementById("val2").value);
const add = num1 + num2;
console.log(add);
// Displays the result in paragraph using dom
document.getElementById("result").innerHTML =
"Addition : " + add;
OUTPUT :
127
• ondblclick attribute:
occurs when a pointing device button is double
clicked over an element
• onmouseover attribute:
event occurs when a mouse is moved onto an
element
128
64
• onmousedown attribute:
event occurs when a mouse button is pressed over an element
• onmouseup attribute:
event occurs when a mouse button is released over an element
• onmouseout attribute:
event occurs when a mouse is moved away from an element
• onmousemove attribute:
event occurs when a mouse is moved while it is over an element
129
• onkeydown attribute:
event occurs when a key is pressed down over an
element
• onkeyup attribute:
event occurs when a key is released over an
element
• onkeypress attribute:
event occurs when a key is pressed and released
over an element
130
65
Modifying Element style
• Modifying an element's style using JavaScript is a common
task in web development.
• You can use JavaScript to dynamically change the appearance
of HTML elements by manipulating their CSS properties.
Here's how you can do it:
Using the ‘style’ Property:
• You can directly access and modify an element's inline style
using the style property.
• This method is suitable for making simple style changes.
131
132
66
Adding or Removing CSS Classes:
• For more complex styling changes or to apply predefined styles, it's
often better to use CSS classes.
• You can add or remove classes using the classList property.
133
134
67
Applying Changes to Multiple Elements:
You can use loops or query selectors to apply style changes to
multiple elements at once.
// Using a loop to apply styles to multiple elements
const elements = document.querySelectorAll(".my-class");
elements.forEach(element => {
element.style.fontSize = "18px";
});
68
• The document tree in the DOM is organized as a tree-like
structure, where each element in the document (such as HTML
tags) is represented as a node in the tree.
• The top node of the tree is the "document" node, which
represents the entire web page. Below it, you have nodes
representing elements, attributes, and text content.
• Elements can have child nodes, which are nested elements
within them.
• This hierarchical structure reflects the nesting and
relationships between different elements in the HTML or XML
document.
137
69
DOM event handling
• DOM (Document Object Model) event handling is a
fundamental aspect of web development that allows you to
respond to interactions and actions that occur within a web
page.
• Events are user actions or occurrences that take place in the
browser, such as clicking a button, typing in an input field,
resizing the window, and more.
• Event handling involves specifying what should happen when
a particular event occurs and then executing the
corresponding code (event handler) in response.
139
70
3. Event Listener:
• An event listener is a piece of code that "listens" for a specific
event on a particular DOM element.
• When the event occurs, the event listener executes a function
(event handler) that you've defined.
4. Event Handler:
• The event handler is the function that gets executed when the
event is triggered.
• It contains the code that responds to the event. This code can
manipulate the DOM, update data, or perform other actions
based on the event.
142
71
• Event handling is crucial for creating interactive and
dynamic web pages.
• It allows you to create responsive user interfaces and
enables users to interact with your web content in
meaningful ways.
• Different event types and event listeners provide
developers with a wide range of possibilities for
creating engaging user experiences.
143
jQuery
• JQuery is Easy to Learn
• JQuery is Lightweight
JavaScript programming.
72
jQuery Cont..
• "write less, do more", JavaScript library.
• perform common tasks on web pages.
• The purpose of jQuery is to make it much easier
to use JavaScript on your website.
• jQuery also simplifies a lot of the complicated
things from JavaScript, like AJAX calls and DOM
manipulation.
jQuery Cont..
The jQuery library contains the following features:
• HTML/DOM manipulation
• CSS manipulation
• HTML event methods
• Effects and animations
• AJAX
• Utilities
146
73
jQuery Cont..
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements
and performing some action on the element(s).
$(selector).action()
147
jQuery Cont..
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
148
74
jQuery Cont..
Adding jQuery to Your Web Pages
149
jQuery Cont..
Downloading jQuery
There are two versions of jQuery available for downloading:
Production version - this is for your live website because it has been
minified and compressed
Development version - this is for testing and development (uncompressed
and readable code)
Both versions can be downloaded from jQuery.com.
<head>
<script src="jquery-3.6.4.min.js"></script>
</head>
150
75
jQuery Cont..
jQuery CDN
If you don't want to download and host jQuery yourself, you
can include it from a CDN (Content Delivery Network).
Google is an example of someone who host jQuery:
Google CDN:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/j
query.min.js"></script>
</head>
151
jQuery Cont..
jQuery Example: To hide Paragraph
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.j
s"> </script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script> </head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
</body>
152
76
jQuery Cont..
• jQuery Example: To change CSS Property
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).css("background-color","Red");
});
});
</script> </head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
</body>
jQuery Cont..
• jQuery Example: To append/Add element
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
> </script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).append("Hello");
});
});
</script> </head>
<body>
<p>If you click on me, I will modify.</p>
<p>Click me away!</p>
</body>
154
77
jQuery Cont..
jQuery Example: To remove element
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).remove();
});
});
</script> </head>
<body>
<p>If you click on me, I will remove.</p>
<p>Click me away!</p>
</body>
155
Angular JS
• AngularJS is a JavaScript framework.
• It can be added to an HTML page with a <script> tag.
• AngularJS extends HTML attributes with Directives,
and binds data to HTML with Expressions.
• Syntax
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/
1.6.4/angular.min.js"> </script>
156
78
Angular JS Cont…
AngularJS Extends HTML
• AngularJS extends HTML with ng-directives.
• The ng-app directive defines an AngularJS
application.
• The ng-model directive binds the value of HTML
controls (input, select, textarea) to application data.
• The ng-bind directive binds application data to the
HTML view.
79
The Model
• The model is responsible for managing application
data.
• It responds to the request from view and to the
instructions from controller to update itself.
The View
• A presentation of data in a particular format,
triggered by the controller's decision to present the
data.
• They are script-based template systems such as JSP,
ASP, PHP and very easy to integrate with AJAX
technology.
160
80
The Controller
The controller responds to user input and
performs interactions on the data model
objects.
The controller receives input, validates it, and
then performs business operations that modify
the state of the data model.
161
Angular JS Cont…
• Steps to create AngularJS
• Step 1 − Load framework- using <Script> tag.
<script src =
"https://ajax.googleapis.com/ajax/libs/
angularjs/1.3.14/angular.min.js"></script>
• Step 2 − Define AngularJS Application using ng-app
directive
<div ng-app = ""> ... </div>
81
Angular JS Cont…
• Step 3 − Define a model name using ng-model
directive
<p>Enter your Name: <input type = "text"
ng-model = "name"></p>
• Step 4 − Bind the value of above model defined using
ng-bind directive.
<p>Hello <span ng-bind = "name"></span>!</p>
163
Angular JS Cont…
AngularJS – Directives
• 1. ng-app − This directive starts an AngularJS
Application. It is also used to load various AngularJS
modules in AngularJS Application.
<div ng-app = ""> ... </div>
• 2. ng-init − This directive initializes application data.
It is used to put values to the variables to be used in
the application.
<div ng-app="" ng-init="firstName='John'">
82
Angular JS Cont…
• 3. ng-model − This directive binds the values of
AngularJS application data to HTML input controls.
<p>Enter your Name: <input type = "text" ng-
model = "name"></p>
165
Angular JS Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/ang
ular.min.js"></script>
<body>
<div ng-app="">
Name: <input type="text" ng-model="name">
<p ng-bind="name"></p>
</div>
</body>
</html>
166
83
Example explained:
AngularJS starts automatically when the web page has
loaded.
Angular JS Cont…
AngularJS Expression
Expressions are used to bind application data to
html.
Expressions are written inside double braces like
{{ expression}}
Using numbers
<p>Expense on Books : {{cost * quantity}} Rs</p>
168
84
Angular JS Cont…
Using strings
<p>Hello {{fname+ “ “ +lname }}</p>
Using object
<p>Roll No: {{student.rollno}}</p>
Using array
<p>Marks(Math): {{marks[3]}}</p>
169
Angular JS Cont…
• AngularJS Expressions –Example
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.
6.4/angular.min.js">
</script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
Output
</html>
My first expression : 10
170
85
Angular JS Cont…
• AngularJS – Controllers
• AngularJS application mainly relies on controllers to
control the flow of data in the application.
• A controller is defined using ng-controller directive
• Each controller accepts $scope as a parameter which
refers to the application/module that controller is to
control.
<div ng-app="myApp" ng-controller="myCtrl">
171
Angular JS Cont…
AngularJS Controllers- Example
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
172
86
Angular JS Cont…
OUTPUT
173
87
88