Unit II

Download as pdf or txt
Download as pdf or txt
You are on page 1of 168

Unit 2:

JAVASCRIPT,
JQUERY and AJAX
JAVASCRIPT
What is JavaScript?

• JavaScript is a high-level, interpreted programming language that


allows for dynamic and interactive web development.

• It is primarily used to add interactivity, validate forms, manipulate


web page content, and create dynamic user experiences.

• JavaScript can be run on the client-side (in the browser) as well as


on the server-side (with the help of Node.js)

• JavaScript is a powerful scripting language primarily used for client-


side web development.

2
Advantages of JavaScript
• Less server interaction: we can validate user input before sending
the page off to the server. This saves server traffic, which means less
load on your server.

• Immediate feedback to the visitors: don't have to wait for a page


reload to see if they have forgotten to enter something.

• Increased interactivity: we can create interfaces that react when the


user hovers over them with a mouse or activates them via the
keyboard.

• Richer interfaces: we can use JavaScript to include such items as


drag-and-drop.
3
Limitations of JavaScript
• We cannot treat JavaScript as a full-fledged programming language.
It lacks the following important features:

• Client-side JavaScript does not allow the reading or writing of files.


This has been kept for security reason.

• JavaScript cannot be used for networking applications because there


is no such support available.

• JavaScript doesn't have any multithreading or multiprocessor


capabilities.

• JavaScript is a lightweight, interpreted programming language that


allows you to build interactivity into otherwise static HTML pages.
4
JavaScript- Syntax
• JavaScript can be implemented using JavaScript statements that are
placed within the <script> ….. </ script> HTML tags in a web page.

• You can place the <script> tags, containing your JavaScript,


anywhere within you web page, but it is normally recommended that
you should keep it within the <head> tags.

• The <script> tag alerts the browser program to start interpreting all
the text between these tags as a script. A simple syntax of your
JavaScript will appear as follows:

<script>
// JavaScript code
</script> 5
Script tag
• 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".

<script language="javascript" type="text/javascript">


JavaScript code
</script>

6
Script tag
If we are using HTML5 then we can skip the type attribute entirely:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script>
</script>
</head>

7
Script tag
If you‟re using HTML5, life is even simpler. You can skip the type attribute
entirely:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<head>
<title>My Web Page</title>
<script>
alert('hello world!');
</script>
</head>

8
Script tag
In many cases, we put the <script> tags in the page‟s <head> in order to
keep our JavaScript code neatly organized in one area of the web page.
However, it‟s perfectly valid to put <script> tags anywhere inside the
HTML of the page.

It‟s even common to put <script> tags just below the closing </body>
tag—this approach makes sure the page is loaded and the visitor sees
it before running any JavaScript.

9
External JavaScript Files
Advantages:
• If it‟s internal javascript, and if we want certain script to be common
in all the web pages a lot of copying and pasting the same code over
and over again will take place, especially if you have a site with
hundreds of pages.
• Secondly, if we ever decide to change or enhance the JavaScript
code, we ill need to locate every page using that JavaScript and
update the code.
• Finally, since all of the code for the JavaScript program would be
located in every web page, each page will be that much larger and
slower to download.
• A better approach is to use an external JavaScript file.
• An external JavaScript file is simply a text file that ends with the file
extension .js, for example navigation.js. The file only includes
JavaScript code and is linked to a web page using the <script> tag. 10
External JavaScript Files
• For example, to add a JavaScript file named navigation.js to your
home page, you might write the following:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script src="navigation.js"></script>
</head>

• The src attribute of the <script> tag points to a file either in your
website or on another website (see the box on the next page). 11
External JavaScript Files
• Note: When adding the src attribute to link to an external JavaScript
file, don‟t add any JavaScript code between the opening and closing
<script> tags. If you want to link to an external JavaScript file and add
custom JavaScript code to a page, use a second set of <script> tags.

For example:

<script src="navigation.js"></script>
<script >
alert('Hello world!');
</script>

12
External JavaScript Files
• In addition, you can attach src="slideshow.js"></script>
external JavaScript files and add
<script>
a JavaScript program to the
same page like this: alert('hello world!');
<!doctype html> </script>
<html> </head>
<head>
• Remember that you must use
<meta charset="UTF-8"> one set of opening and closing
<title>My Web Page</title> <script> tags for each external
<script JavaScript file.
src="navigation.js"></script>
<script
13
External JavaScript Files
• Note: When adding the src attribute to link to an external JavaScript
file, don‟t add any JavaScript code between the opening and closing
<script> tags. If you want to link to an external JavaScript file and add
custom JavaScript code to a page, use a second set of <script> tags.

For example:

<script src="navigation.js"></script>
<script >
alert('Hello world!');
</script>

14
JavaScript Datatypes
• Numbers - are values that can be processed and calculated. You
don't enclose them in quotation marks. The numbers can be either
positive or negative. Example : 123, 120.50 etc.

• Strings - are a series of letters and numbers enclosed in quotation


marks. JavaScript uses the string literally; it doesn't process it. You'll
use strings for text you want displayed or values you want passed
along. Example : "This text string"

• Boolean (true/false) - lets you evaluate whether a condition meets


or does not meet specified criteria.

• Null - is an empty value. null is not the same as 0 -- 0 is a real,


calculable number, whereas null is the absence of any value.
15
JavaScript Variable Names
• While naming your variables in JavaScript, keep the following rules in
mind.

• We should not use any of the JavaScript reserved keywords as a


variable name. For example, break or boolean variable names are not
valid.

• JavaScript variable names should not start with a numeral (0-9).


They must begin with a letter or an underscore character. For
example, 123test is an invalid variable name but 123test is a valid one.
JavaScript variable names are case-sensitive. For example, Name
and name are two different variables.

16
JavaScript Variables
• Before you use a variable in a JavaScript program, you must declare
it. Variables are declared with the var keyword as follows.

<script type="text/javascript">
var money;
var name;
</script>

• You can also declare multiple variables with the same var keyword as
follows: var money, name;

17
JavaScript Variables
• Storing a value in a variable is called variable initialization. You can
do variable initialization at the time of variable creation or at a later
point in time when you need that variable.

• For instance, you might create a variable named money and assign
the value 2000.50 to it later. For another variable, you can assign a
value at the time of initialization as follows.

<script type="text/javascript">
var name = "Ali";
var money;
money = 2000.50;
</script>
18
JavaScript Variable Scope
• Variables declared within a function are local to that function.
• Variables declared outside of any function are global variables.

19
<html> Output :
<body> Welcome
<script> XYZ
var firstname;
firstname="Welcome"; The script above declares a variable,
document.write(firstname); assigns a value to it, displays the value,
document.write("<br />"); change the value, and displays the
firstname="XYZ"; value again.
document.write(firstname);
</script>
<p>The script above declares a
variable,
assigns a value to it, displays the value,
change the value,
and displays the value again.</p>
</body>
</html>

20
Conditional Statements
• In JavaScript we have the following conditional statements:

• if statement - use this statement if you want to execute some code


only if a specified condition is true
• if...else statement - use this statement if you want to execute some
code if the condition is true and another code if the condition is false
• if...else if....else statement - use this statement if you want to select
one of many blocks of code to be executed.
• switch statement - use this statement if you want to select one of
many blocks of code to be executed

21
Conditional Statements
• If Statement You should use the if statement if you want to execute
some code only if a specified condition is true.

Syntax:
if (condition)
{
code to be executed if condition is true
}

Notice that there is no ..else.. in this syntax. You just tell the
code to execute some code only if the specified condition is
true.
22
Conditional Statements
The following code prints a "Good morning" greeting if the
time is less than 10

<script>
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
23
Conditional Statements
• If...else Statement
Execute some code if a condition is true and another code if the
condition is not true
Syntax:
if (condition)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is not true
}
24
Conditional Statements
Example: If the time is less than 10, you will get a "Good morning" greeting.
Otherwise you will get a "Good day" greeting.

<script >
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script> 25
Conditional Statements
• If...else Statement
Execute some code if a condition is true and another code if the
condition is not true
Syntax:
if (condition1)
{
//code to be executed if condition1 is true
}
else if (condition2)
{
//code to be executed if condition2 is true
}
else
{
//code to be executed if condition1 and condition2 are not true
}
26
Conditional Statements
Example:
<script>
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{ document.write("Hello World!"); }
27
Conditional Statements
• The JavaScript Switch Statement

Syntax:
switch(n)
{
case 1:
//execute code block 1
break;
case 2:
//execute code block 2
break;
default:
// code to be executed if n is different from case 1 and 2
}

28
Conditional Statements
Example: document.write("I'm looking forward to
<script type="text/javascript"> this weekend!");
var d=new Date(); }
theDay=d.getDay(); </script>
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
29
Different Kinds of Loops
In JavaScript there are two different kind of loops:
for - loops through a block of code a specified number of times
while - loops through a block of code while a specified condition is true

The for Loop


The for loop is used when you know in advance how many times the
script should run.

Syntax:

for (intitialization;condition;increment/decrement)
{
//code to be executed
}
30
Different Kinds of Loops
Example
Explanation: The example below defines a loop that starts with i=0. The
loop will continue to run as long as i is less than, or equal to 10. i will
increase by 1 each time the loop runs.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html> 31
Different Kinds of Loops
In JavaScript, the for...in loop is used to iterate over the properties of an
object. It allows you to loop through the enumerable properties of an
object, including inherited properties.

syntax:
for (variable in object)
{
// code to be executed
}

32
Different Kinds of Loops
Example
const person = {
name: 'John',
age: 30,
gender: 'male'
};

for (let prop in person) {


console.log(prop + ': ' + person[prop]);
}

In this example, the for...in loop iterates over each property in the person object.
On each iteration, the prop variable is assigned the name of the current
property, and person[prop] retrieves the value associated with that property.

33
Different Kinds of Loops
The for...of loop in JavaScript is used to iterate over iterable objects,
such as arrays, strings, sets, etc.
The for...of loop assigns the value of each iterable element to a variable for each
iteration. Here's the basic syntax:
for (variable of iterable)
{
// code to be executed
}

Here's an example to illustrate the usage of the for...of loop:


const colors = ['red', 'green', 'blue'];

for (let color of colors) {


console.log(color);
}

34
Different Kinds of Loops
• In this example, we have an array called colors containing three
elements. The for...of loop iterates over each element of the colors
array. On each iteration, the color variable is assigned the value of
the current element. We then log the color variable to the console.

• The loop continues until it has iterated over all the elements of the
iterable (colors array in this case), and each element is accessed
using the color variable.

• Note that the for...of loop is specifically designed for iterating over
values, not for accessing the index or other properties of the iterable
object.

35
Different Kinds of Loops
1. The while loop
2. The while loop is used when you want the loop to execute and
continue executing while the specified condition is true.
while (condition)
{
//code to be executed
}

The example below defines a loop that starts with i=0. The
loop will continue to run as long as i is less than, or equal to
10. i will increase by 1 each time the loop runs.

36
Different Kinds of Loops
Example:
</html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html> 37
Different Kinds of Loops
The do...while Loop

The do...while loop is a variant of the while loop. This


loop will always execute a block of code ONCE, and
then it will repeat the loop as long as the specified
condition is true.

This loop will always be executed at least once, even if


the condition is false, because the code is executed
before the condition is tested.

38
Different Kinds of Loops
The do...while Loop

The do...while loop is a variant of the while loop. This


loop will always execute a block of code ONCE, and
then it will repeat the loop as long as the specified
condition is true.

This loop will always be executed at least once, even if


the condition is false, because the code is executed
before the condition is tested.

39
Different Kinds of Loops
The do...while Loop document.write("The number is
do{ " + i);
document.write("<br />");
// code to be executed i=i+1;
}while (condition); }
while (i<0);
Example: </script>
<html> </body>
<body> </html>
<script type="text/javascript">
var i=0;
do

{ 40
JavaScript Functions
• A function (also known as a method) is a self-
contained piece of code that performs a particular
"function".

• Function is a reusable code-block that will be


executed by an event, or when the function is
called.

• To keep the browser from executing a script when


the page loads, you can put your script into a
function.
41
JavaScript Functions
• A function contains code that will be executed by
an event or by a call to that function.

• You may call a function from anywhere within the


page (or even from other pages if the function is
embedded in an external .js file).

• Functions can be defined both in the <head> and in


the <body> section of a document.
• However, to assure that the function is read/loaded
by the browser before it is called, it could be wise to
put it in the <head> section. 42
JavaScript Functions
The syntax for creating a function is:
function functionname(var1, var2 ,..., varX)
{
// code to be executed when function is called
}
var1, var2, etc are variables or values passed into the
function. The { and the } defines the start and end of
the function.
A function with no parameters must include the
parentheses () after the function name.
43
JavaScript Functions
The return Statement
The return statement is used to specify the value that is returned from
the function.
So, functions that are going to return a value must use the return
statement.

Example
The function below should return the product of two numbers (a and b):
function prod(a, b)
{
x=a*b;
return x;
}
When you call the function above, you must pass along two parameters:
product=prod(2,3); The returned value from the prod() function is 6, and it will
be stored in the variable called product. 44
JavaScript Functions
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!” onclick="displaymessage()" >
</form>
</body>
</html>

45
JavaScript Functions
If the line: alert("Hello world!!") in the example above
had not been put within a function, it would have
been executed as soon as the line was loaded.

Now, the script is not executed before the user hits


the button. We have added an onClick event to the
button that will execute the function
displaymessage( ) when the button is clicked.

46
Event and Event Handlers
Event Handlers are JavaScript methods, i.e. functions
of objects, that allow us as JavaScript programmers
to control what happens when events occur.
Directly or indirectly, an Event is always the result of
something a user does.
For example, Event Handlers like onClick and
onMouseOver that respond to mouse actions.
Another type of Event, an internal change-of-state to
the page (completion of loading or leaving the
page). An onLoad Event can be considered an
indirect result of a user action.
47
Event and Event Handlers
An Event is merely something that happens -
something that it is initiated by an Event Handler
(onClick, onMouseOver, etc...)

1. The elements on a page which can trigger events


are known as "targets" or "target elements," and we
can easily understand how a button which triggers
a Click event is a target element for this event.
2. Typically, events are defined through the use of
Event Handlers, which are bits of script that tell the
browser what to do when a particular event occurs
at a particular target. 48
Event and Event Handlers
These Event Handlers are commonly written as
attributes of the target element's HTML tag.
The Event Handler for a Click event at a form field
button element is quite simple to understand:

<INPUT TYPE="button" NAME="click1" VALUE="Click me


for fun! " onClick="eventhandlercode">

49
Event and Event Handlers
The eventhandlercode portion of this example is any
valid JavaScript and it will be executed when the
specified event is triggered at this target element.
This particular topic will be continued in Incorporating
JavaScripts into your HTML pages.

There are "three different ways" that Event Handlers


can be used to trigger Events or Functions.

50
Event and Event Handlers
Method 1 (Link Events):
Places an Event Handler as an attribute within an <A
HREF= > tag, like this:
<A HREF=“abc.html" onMouseOver="doSomething()">
... </A>

You can use an Event Handler located within an <A


HREF= > tag to make either an image or a text link
respond to a mouseover Event. Just enclose the
image or text string between the <A HREF= > and the
</A> tags.
51
Event and Event Handlers
Whenever a user clicks on a link, or moves her cursor over one,
JavaScript is sent a Link Event. One Link Event is called onclick,
and it gets sent whenever someone clicks on a link.
Another link event is called onmouseover. This one gets sent
when someone moves the cursor over the link.

You can use these events to affect what the user sees on a
page. Here's an example of how to use link events.
<a href="javascript:void('')"
onclick="open('index.htm', 'links', 'height=200,width=200');">How
to Use Link Events
</A>

52
Event and Event Handlers
Here are the three lines of interest:

1. <a href="#" onClick="alert(„Hello');">Click on me!</a>

The href attribute with the value "#" is a relative URL that points to the
current page or simply represents a placeholder for a link.

The onClick attribute is an event handler attribute that specifies


JavaScript code to be executed when the element is clicked. In this
case, the JavaScript code alert('Hello'); is provided as the value. The
alert() function creates a dialog box with the message "Hello".

So, when the user clicks on the "Click on me!" link, the JavaScript code
alert('Hello'); is executed, and a dialog box with the message "Hello" will
pop up. 53
Event and Event Handlers
2. <a href="javascript:void('')" onClick="alert(„Hello!');">
Click on me! </A>

<A HREF="javascript:void('')" tells the browser not to go anywhere


- it "deadens" the link when you click on it. HREF="javascript: is the
way to call a function when a link (hyperlink or an HREFed
image) is clicked.

This technique is often used to create links that trigger


JavaScript functions without causing any navigation or
refreshing of the page. Developers can add their desired
JavaScript code or function to be executed when the link is
clicked, replacing the empty string '' with the appropriate
JavaScript code. 54
Event and Event Handlers
3. <a href="javascript:alert(„Hello!')" >Click on me!</A>

In this case, when the user clicks on the "Click on me!" link, the
JavaScript code alert('Hello!') will be executed. The alert()
function creates a dialog box with the message "Hello!".

55
Method 2 (Actions within FORMs):
The entire code for the function could appear in quotation marks
rather than a function call:

<input type="text" onchange="if (this.value <= 5)


{
alert("Please enter a number greater than 5");
}">

To separate multiple commands in an Event Handler, use


semicolons

<INPUT TYPE="text" onchange="alert(„Thanks for the entry.‟);


confirm(„Do you want to continue?‟);"> 56
Method 2 (Actions within FORMs):
The second technique we've seen for triggering a Function in
response to a mouse action is to place an onclick Event Handler
inside a button type form element, like this:

<form>
<input type="button" onclick=“reverse( )">
</form>

57
Method 3 (BODY onLoad & onUnLoad):
• The third technique is to us an Event Handler to ensure that all
required objects are defined involve the onLoad and
onUnLoad.

• These Event Handlers are defined in the <BODY> or


<FRAMESET> tag of an HTML file and are invoked when the
document or frameset are fully loaded or unloaded.

• If you set a flag within the onLoad Event Handler, other Event
Handlers can test this flags to see if they can safely run, with
the knowledge that the document is fully loaded and all
objects are defined.

58
Method 3 (BODY onLoad & onUnLoad):
var loaded = false;

function doit( )
{
alert('Everything is "loaded" and loaded = ' + loaded);
}

loaded = true; // Update the value of the 'loaded' variable


doit(); // Call the 'doit' function

59
Method 3 (BODY onload & onunload):
In this, the loaded variable is initially set to false. Then, the doit( )
function is defined to display an alert box with the message

"Everything is 'loaded' and loaded = false"

After defining the function, the code updates the value of the
loaded variable to true, and then calls the doit( ) function. When
executed, it will display an alert box with the message
"Everything is 'loaded' and loaded = true".

60
Method 3 (BODY onload & onunload):
<body onload="loaded = true;">

-- or --
<body onload="window.loaded = true;">
<form>
<input type="button" value="press me“ onclick="if (loaded == true)
doit( );">

-- or --
<input type="button" value="press me“
onclick="if (window.loaded == true) doit();">

-- or --
<input type="button" value="press me“ onclick="if (loaded) doit();">
</form> </body>
61
Event Handler:

62
JavaScript Arrays :
1. An array object is used to create a database-like structure within a
script. Grouping data points (array elements) together makes it
easier to access and use the data in a script.

2. There are methods of accessing actual databases (which are


beyond the scope of this series) but here we're talking about small
amounts of data.
3. Arrays in JavaScript are data structures used to store multiple values
in a single variable. They are indexed collections of elements, where
each element is identified by an index starting from 0.

Declaration and Initialization: Arrays can be declared and initialized


using the array literal syntax [] or the Array constructor.

63
JavaScript Arrays :
// Empty array
let emptyArray = [];

// Array with initial values


let numbers = [1, 2, 3, 4, 5];

// Array using the Array constructor


let fruits = new Array("apple", "banana", "orange");

64
JavaScript Arrays :
Accessing Elements: Elements within an array can be accessed using
their index , which starts from 0. The array[index] syntax is used to
access specific elements.

let fruits = ["apple", "banana", "orange"];


console.log(fruits[0]); // Output: "apple"
console.log(fruits[2]); // Output: "orange”

65
JavaScript Arrays :
Modifying Elements: Elements within an array can be modified by
assigning new values using their index.

let fruits = ["apple", "banana", "orange"];


fruits[1] = "kiwi";
console.log(fruits); // Output: ["apple", "kiwi", "orange"]

66
JavaScript Arrays :
Length Property: The length property of an array returns the number of
elements in the array.

let numbers = [1, 2, 3, 4, 5];


console.log(numbers.length); // Output: 5

67
JavaScript Arrays :
Array Methods: JavaScript provides a variety of methods to manipulate
arrays. Some common methods include push( ), pop(), shift( ), unshift(),
slice(), splice(), concat(), join(), sort(), and reverse(), among others.

let numbers = [1, 2, 3];


numbers.push(4); // Adds 4 at the end of the array
console.log(numbers); // Output: [1, 2, 3, 4]

numbers.pop(); // Removes the last element (4) from the array


console.log(numbers); // Output: [1, 2, 3]

68
JavaScript Arrays :
Iterating over Arrays: Arrays can be iterated using loops like for, while, or
for...of.

let fruits = ["apple", "banana", "orange"];

// Using for loop


for (let i = 0; i < fruits.length; i++)
{
console.log(fruits[i]);
}

// Using for...of loop


for (let fruit of fruits)
{
console.log(fruit);
} 69
JavaScript Arrays :
Multidimensional Arrays: Arrays in JavaScript can also be
multidimensional, meaning they can contain other arrays as elements.
This allows you to create matrices or store structured data.

let matrix = [

[1, 2, 3],
[4, 5, 6],
[7, 8, 9]

];

console.log(matrix[0][1]); // Output: 2
console.log(matrix[2][0]); // Output: 7
70
Document Object Model (DOM)

1. DOM stands for Document Object Model. It is a programming interface


for HTML and XML documents.

2. The DOM represents the structure of a document as a tree-like object,


where each element, attribute, and piece of text in the document is
represented as a node in the tree.

3. The DOM provides a way for programs and scripts to access,


manipulate, and update the content, structure, and style of a web
page. It allows developers to dynamically modify the document's
elements, attributes, and text through scripting languages such as
JavaScript.
71
Document Object Model (DOM)
<!DOCTYPE html>
<html>
<head>
<title>Parent-Child Relationships</title>
</head>
<body>
<div id="parent">
<h1>Parent Node</h1>
<p>Some text content.</p>
<ul>
<li>Child 1</li>
<li>Child 2</li>
<li>Child 3</li>
</ul>
</div>
<script>
72
Document Object Model (DOM)
var parentElement = document.getElementById('parent');

// Accessing child nodes


var childNodes = parentElement.childNodes;
console.log(childNodes); // Output: NodeList [text, h1, text, p, text, ul, text]

// Accessing specific child elements


var headingElement = parentElement.querySelector('h1');
console.log(headingElement); // Output: <h1>Parent Node</h1>

var listElement = parentElement.querySelector('ul');


console.log(listElement); // Output: <ul>...</ul>

// Accessing parent node


var listItemElement = listElement.firstElementChild;
var parentNode = listItemElement.parentNode;
console.log(parentNode); // Output: <ul>...</ul>
</script>
</body>
</html> 73
Document Object Model (DOM)
Here are some key points about the DOM:

1. Tree-like structure: The DOM represents an HTML or XML document as


a hierarchical structure, with the root node at the top and child nodes
branching out from it.

2. Nodes: The elements, attributes, and text in the document are


represented as nodes in the DOM tree. There are various types of
nodes, including element nodes, attribute nodes, and text nodes.

3. Relationship between nodes: Nodes in the DOM have parent-child


relationships, where an element node can have child nodes (other
elements or text nodes) and a parent node.

74
Document Object Model (DOM)
1. Access and manipulation: The DOM provides methods and properties
that allow developers to access and manipulate the nodes and their
attributes, styles, and content. This enables dynamic modification of
the document structure and content.

2. Cross-platform and language-independent: The DOM is a language-


independent interface, meaning it can be used with different
programming languages. It is commonly associated with JavaScript
for web development, but other programming languages can also
interact with the DOM.

3. By using the DOM, developers can create interactive web pages,


update content dynamically, handle events, and respond to user
actions. It serves as a bridge between the web page's structure and the
programming language used to manipulate it, enabling dynamic and
interactive web applications. 75
Document Object Model (DOM)
<!DOCTYPE html> document.getElementById('heading');
<html> headingElement.style.color = 'red';
<head>
<title>DOM Example</title> var listItemElements =
</head> document.getElementsByTagName('li');
<body> for (var i = 0; i <
<h1 id="heading">Hello, DOM!</h1> listItemElements.length; i++) {
<p>Here's a paragraph.</p> listItemElements[i].style.fontWeight =
<ul> 'bold';
<li>Item 1</li> }
<li>Item 2</li> </script>
<li>Item 3</li> </body>
</ul> </html>
<script>
// JavaScript code to manipulate the
DOM
var headingElement =
76
Document Object Model (DOM)
• In this example, we have an HTML document that contains a heading
(<h1>), a paragraph (<p>), and an unordered list (<ul>) with three list
items (<li>).

• To manipulate the DOM, we use JavaScript embedded within a <script>


tag. Here's what the JavaScript code does:
• Accessing and modifying an element: We use the getElementById()
method to access the heading element with the ID "heading". Then, we
modify its style property to change the color to red.
• Accessing and modifying multiple elements: We use the
getElementsByTagName() method to access all the <li> elements
within the document. Then, we loop through each list item and modify
its style property to set the font weight to bold.

77
Document Object Model (DOM)
• By running this example, the JavaScript code manipulates the DOM
dynamically. The heading's color changes to red, and all list items
become bold.

• This example demonstrates how the DOM allows us to access and


manipulate elements, their attributes, and their styles using JavaScript.
We can selectively modify specific elements or apply changes to
multiple elements based on their tag names, classes, or other
attributes. The DOM provides a powerful interface for creating dynamic
and interactive web pages.

78
getElementById :
• getElementById is a method in the Document Object Model (DOM)
interface that allows you to retrieve an element from an HTML
document based on its unique id attribute value. It is a commonly used
method in JavaScript to access and manipulate specific elements in
the DOM.

Syntax for using getElementById :

var element = document.getElementById('idValue');

79
getElementById :
In the above syntax:

1. document refers to the current HTML document object.


2. getElementById is the method name.
3. 'idValue' is the value of the id attribute of the element you want to
retrieve.
4. The getElementById method searches the entire document for an
element with the specified id value and returns the matching element.
If no element is found with the provided id, it returns null.

80
getElementById :
<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<div id="myDiv">This is a div element.</div>

<script>
var element = document.getElementById('myDiv');
console.log(element.textContent); // Output: "This is a div element."
</script>
</body>
</html>
81
getElementById :
• In this example, the getElementById method is used to retrieve the
<div> element with the id attribute set to "myDiv". The returned element
is stored in the element variable.

• We then access the textContent property of the retrieved element,


which contains the text content within the <div>. In this case, it will
output "This is a div element." to the console.

• Note that the id attribute should be unique within the document, as it is


meant to identify a specific element. If there are multiple elements with
the same id, the method will only retrieve the first matching element it
encounters during the search.

82
addEventListener :
• addEventListener is a method in JavaScript that allows you to attach
event handlers to DOM elements. It is used to register a specific
function (known as an event handler or callback) to be executed when
a particular event occurs on the specified element.

• Here's the syntax for using addEventListener:

element.addEventListener(event, callback, options);

83
addEventListener :
In the above syntax:

1. element refers to the DOM element to which you want to attach the
event handler.
2. event is a string that specifies the name of the event (e.g., "click",
"mouseover", "keydown").
3. callback is the function that gets executed when the specified event
occurs on the element.
4. options (optional) is an object that specifies additional options for the
event handling, such as capturing or once.

84
addEventListener :
<!DOCTYPE html>
<html>
<head>
<title>addEventListener Example</title>
</head>
<body>
<button id="myButton">Click Me</button>

<script>
var buttonElement = document.getElementById('myButton');

buttonElement.addEventListener('click', function() {
console.log('Button clicked');
});
</script>
</body>
</html>
85
addEventListener :
In this example, we have an HTML document with a button element. The
addEventListener method is used to attach a click event handler to the button.

When the button is clicked, the callback function (anonymous function in this
case) is executed. In the example, it logs the message "Button clicked" to the
console.

The addEventListener method allows you to handle a wide range of events on DOM
elements, including mouse events, keyboard events, form events, and more. It is a
powerful feature that enables interactivity and responsiveness in web applications.

By attaching event listeners using addEventListener, you can have multiple event
handlers for the same element and event, respond to user actions, and perform
specific actions or logic in response to events.

86
Event Bubbling And Event Capturing
• In JavaScript, event bubbling and event capturing are two different
mechanisms that describe how events propagate through the DOM
(Document Object Model) hierarchy.

• Event Bubbling: Event bubbling is the most common event


propagation mechanism in JavaScript.

• With event bubbling, an event is first handled at the target element


where it originated, and then it moves up the DOM tree, triggering event
handlers on each ancestor element until it reaches the root of the
document (or until the event is explicitly stopped).

87
Here's an example that demonstrates event bubbling:
<!DOCTYPE html>
<html>
<head>
<title>Event Bubbling Example</title>
</head>
<body>
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
var parentElement = document.getElementById('parent');
var childElement = document.getElementById('child');

parentElement.addEventListener('click', function() {
console.log('Parent clicked');
});

childElement.addEventListener('click', function() {
console.log('Child clicked');
});
</script> </body> </html> 88
Event Bubbling And Event Capturing
1. In this example, we have a parent <div> element with an ID of "parent"
and a child <button> element with an ID of "child".
2. When you click the button, the click event is triggered on the button
itself, and then it bubbles up to the parent <div> element.

3. The event handlers attached to both elements are invoked, resulting in


the following output in the console:

OUTPUT:
Child clicked
Parent clicked

89
Event Bubbling And Event Capturing
1. Event Capturing: Event capturing is the reverse mechanism of event
bubbling. With event capturing, the event starts at the root of the
document and travels down the DOM tree, triggering event handlers on
each ancestor element until it reaches the target element (or until the
event is explicitly stopped).

2. To demonstrate event capturing, we can modify the previous example:

90
Here's an example that demonstrates event capturing :
<!DOCTYPE html>
<html>
<head>
<title>Event Capturing Example</title>
</head>
<body>
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
var parentElement = document.getElementById('parent');
var childElement = document.getElementById('child');

parentElement.addEventListener('click', function() {
console.log('Parent clicked');
}, true);

childElement.addEventListener('click', function() {
console.log('Child clicked');
}, true);
</script> </body> </html> 91
Event Bubbling And Event Capturing
1. In this example, we have the same parent-child structure as before.
However, we have added an optional third argument (true) to the
addEventListener method, which enables event capturing.

2. When you click the button, the click event is triggered at the root of the
document and propagates down to the button element. The event
handlers attached to both elements are invoked, resulting in the
following output in the console:

OUTPUT:

Parent clicked
Child clicked

92
Event Bubbling And Event Capturing
1. In this case, when the button is clicked, the click event handler for the
parent element is executed first, followed by the click event handler for
the child element, and finally the click event handler for the button. The
event is captured from the parent to the target element.

1. To summarize, event bubbling is the default mechanism where events


propagate from the target element up the DOM tree, while event
capturing is an alternative mechanism where events propagate from
the root of the document down to the target element. Both
mechanisms allow multiple elements to handle the same event, but in
a different order.

93
JavaScript Closures :
• Closures are a powerful concept in JavaScript that allows functions to
retain access to variables from their outer lexical environment, even
after the outer function has finished executing.

• In simpler terms, a closure is formed when an inner function has access


to variables defined in its outer function, even after the outer function
has returned.

• Here's an example to illustrate closures:

94
JavaScript Closures :
function greet(name)
{
var greeting = 'Hello';

function sayHello( )
{
console.log(greeting + name + '!');
}

return sayHello;
}

var greetClosure = greet('John');


greetClosure( ); // Output: "Hello, John!"
95
JavaScript Closures :
• The given code snippet defines a function called greet that takes a
name parameter. Inside the greet function, there is a nested function
called sayHello which logs a greeting message to the console, using
the greeting variable and the provided name.

• When greet is called with the argument 'John', it returns the sayHello
function. The returned function is assigned to the variable
greetClosure.

• Finally, greetClosure() is called, which executes the returned sayHello


function. This will print the message "Hello, John!" to the console.

• This example illustrates how closures can be used to create functions that
remember the values of variables from their outer scope, enabling data
encapsulation and preserving state even after the outer function has
completed its execution. 96
JavaScript Closures :
function outerFunction() {
var outerVariable = 'I am from the outer function';

function innerFunction() {
console.log(outerVariable);
}

return innerFunction;
}

var closure = outerFunction();


closure(); // Output: "I am from the outer function"

97
JavaScript Closures :
• In this example, outerFunction declares a variable called outerVariable
and defines an inner function called innerFunction. Inside innerFunction,
we try to access outerVariable. Even though outerFunction has finished
executing and outerVariable should be out of scope, the closure allows
innerFunction to still access and use outerVariable.

• When we call outerFunction and assign the returned value to closure,


closure becomes a reference to the innerFunction. We can then invoke
closure, and it will successfully log the value of outerVariable to the
console.

• The key idea behind closures is that functions in JavaScript not only
have access to their own scope but also have access to variables from
their outer scope.
98
JavaScript Closures :
• The key idea behind closures is that functions in JavaScript not only
have access to their own scope but also have access to variables from
their outer scope. This behavior is made possible by the way JavaScript
handles lexical scoping and how it allows functions to "remember" their
lexical environment, forming closures.

• Closures are often used to create private variables and encapsulate


data within functions. They enable advanced programming techniques
like currying, memoization, and creating modules with private and
public methods.

99
Introduction to jQuery
1. A JavaScript library is a collection of JavaScript code that provides
simple solutions to many of the mundane, day-to-day details of
JavaScript. Think of it as a collection of prewritten JavaScript functions
that you add to your web page.

2. These functions make it easy to complete common tasks. In many


cases, you can replace many lines of your own JavaScript
programming (and the hours required to test them) with a single
function from a JavaScript library.

100
What is jQuery?

• jQuery is a fast and concise JavaScript Library created by John Resig


with a motto: Write less, do more.

• jQuery simplifies HTML document traversing, event handling, animating,


and Ajax interactions for rapid web development.

• jQuery is a JavaScript toolkit designed to simplify various tasks by


writing less code.

101
What is jQuery?

• jQuery is a fast and concise JavaScript Library created by John Resig


with a motto: Write less, do more.

• jQuery simplifies HTML document traversing, event handling, animating,


and Ajax interactions for rapid web development.

• jQuery is a JavaScript toolkit designed to simplify various tasks by


writing less code.

102
Features of jQuery?
1. Here is the list of important core features supported by jQuery:

2. DOM manipulation: The jQuery made it easy to select DOM elements,


negotiate them and modifying their content by using cross-browser
open source selector engine called Sizzle.

3. Event handling: The jQuery offers an elegant way to capture a wide


variety of events, such as a user clicking on a link, without the need to
clutter the HTML code itself with event handlers.

4. AJAX Support: The jQuery helps you a lot to develop a responsive and
feature-rich site using AJAX technology.

103
Features of jQuery?

1. Animations: The jQuery comes with plenty of built-in animation effects


which you can use in your websites.

2. Lightweight: The jQuery is very lightweight library - about 19KB in size


(Minified and gzipped).

3. Cross Browser Support: The jQuery has cross-browser support, and


works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

4. Latest Technology: The jQuery supports CSS3 selectors and basic


XPath syntax.

104
How to use jQuery?

There are two ways to use jQuery.

1. Local Installation − You can download jQuery library on your local


machine and include it in your HTML code.

2. CDN Based Version − You can include jQuery library into your HTML
code directly from Content Delivery Network (CDN).

105
Local Installation :
1. Go to the https://jquery.com/download/ to download the latest version available.
2. Now, insert downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery.

Example
Now, you can include jquery library in your HTML file as follows:
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="/jquery/jquery-2.1.3.min.js"></script>

<script type="text/javascript">
$(document).ready(function()
{
document.write("Hello, World!");
});
</script> </head>

<body>
<h1>Hello</h1>
</body> </html> 106
CDN Based Version:
You can include jQuery library into your HTML code directly from Content Delivery Network
(CDN). Google and Microsoft provides content deliver for the latest version.

Example
1. Now let us rewrite above example using jQuery library from Google CDN.
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript“
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
document.write("Hello, World!");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body> 107
Selectors:
1. The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us
quickly and easily access elements or groups of elements in the Document Object Model
(DOM).
2. A jQuery Selector is a function which makes use of expressions to find out matching
elements from a DOM, based on the given criteria.

The $( ) Factory Function

All type of selectors available in jQuery, always start with the dollar sign and parentheses:$().
The factory function $() makes use of the following three building blocks while selecting
elements in a given document:

108
109
Selectors:
Example
1. Following is a simple example which makes use of Tag Selector. This would select all the
elements with a tag name p.
<html>
<head>
<title>the title</title>
<script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">

$(document).ready(function() {
var pars = $("p");
for( i=0; i<pars.length; i++ ){
alert("Found paragraph: " + pars[i].innerHTML);
}
});

</script>
</head>
<body>
<div>
<p class="myclass">This is a paragraph.</p>
<p id="myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div> </body> </html>
110
How to Use Selectors?
The selectors are very useful and would be required at every step while using jQuery. They get
the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.

111
How to Use Selectors?

jQuery - Element Name Selector


Description
1. The element selector selects all the elements that have a tag name of T.
Syntax
$('tagname')
tagname − Any standard HTML tag name like div, p, em, img, li etc.

Example

$('p') − Selects all elements with a tag name of p in the document.


$('div') − Selects all elements with a tag name of div in the document.

112
How to Use Selectors?
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select all the divisions */
$("div").css("background-color", "yellow");
});
</script>
</head>

113
Example:
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select all the divisions */
$("div").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html> 114
jQuery - Element ID Selector
The element ID selector selects a single element with the given id attribute.

Syntax
$('#elementid')

Elementid: This would be an element ID. If the id contains any special characters like periods or
colons you have to escape those characters with backslashes.

Example

$('#myid') − Selects a single element with the given id myid.


$('div#yourid') − Selects a single division with the given id yourid.

115
jQuery - Element ID Selector
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select second division only*/
$("#div2").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>

116
jQuery - Element Class Selector
The element ID selector selects a single element with the given id attribute.

Syntax
$('.classid')

classid − This is class ID available in the document.

Example

1. $('.big') − Selects all the elements with the given class ID big.
2. $('p.small') − Selects all the paragraphs with the given class ID small.
3. $('.big.small') − Selects all the elements with a class of big and small.

117
jQuery - Element Class Selector
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select second division only*/
$(".big").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div> Example would select all divisions with class
<div class="medium" id="div2"> .big and will apply yellow color to its
<p>This is second division of the DOM.</p>
</div>
background
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>

118
jQuery - Universal Selector
The universal selector selects all the elements available in the document.

Syntax
$('*')

Example

1. $('*') selects all the elements available in the document.

119
jQuery - Universal Selector
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select all the elements */
$("*").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p> Example would select all the elements and will
</div>
<div class="medium" id="div2"> apply yellow color to their background. Try to
<p>This is second division of the DOM.</p> understand that this selector will select every
</div> element including head, body etc.
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>

120
jQuery - Multiple Elements Selector
1. This Multiple Elements selector selects the combined results of all the specified selectors E, F
or G.
2. You can specify any number of selectors to combine into a single result. Here order of the
DOM elements in the jQuery object aren't necessarily identical.

Syntax
$('E, F, G,....')

E − Any valid selector


F − Any valid selector
G − Any valid selector

Example

1. $('div, p') − selects all the elements matched by div or p.


2. $('p strong, .myclass') − selects all elements matched by strong that are descendants of
an element matched by p as well as all elements that have a class of myclass.
3. $('p strong, #myid') − selects a single elements matched by strong that is descendant of
an element matched by p as well as element whose id is myid.
121
jQuery - Universal Selector
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".big, #div3").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
Example would select elements with class ID
<div class="medium" id="div2">
<p>This is second division of the DOM.</p> big and element with ID div3 and will apply
</div> yellow color to its background
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>
122
jQuery filter() Method
The filter() method is used to filter out all the elements that do not match
the selected criteria and those matches will be returned.

Syntax:
$(selector).filter(criteria, function(index))

Parameters:
criteria : It specifies a selector expression, a jQuery object or one or more
elements to be returned from a group of selected elements.

function(index) : It specifies a function to run for each element in the set.


If the function returns true, the element is kept. Otherwise, it is removed.

index : The index position of the element in the set.


NOTE : To specify more than one criteria, use a comma. 123
jQuery filter() Method
<html>
<head>
<title>FILTER METHOD</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
$("li").filter(".firstyear, .secondyear").css("color", "red").css("background-color", "yellow");
});
</script> </head>
body>
<ul>
<li class="firstyear">First sem</li>
<li class="firstyear">Second sem</li>
<li class="vacation">Vacation</li>
<li class="secondyear">Third sem</li>
<li class="secondyear">Fourth sem</li>
</ul>
</body>
</html>
124
Program : Filtering Even Numbers
<!DOCTYPE html>
<html>
<head>
<title>Filter Even Numbers</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { The provided HTML and
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; JavaScript code is a simple
const evenNumbers = numbers.filter(function(num) program that filters even numbers
{ from the given array and displays
return num % 2 === 0; the result on the web page as:
});
Even Numbers: 2, 4, 6, 8, 10
$("#result").text("Even Numbers: " + evenNumbers.join(", "));
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html> 125
What are jQuery Events?
A jQuery Event is the result of an action that can be detected by jQuery
(JavaScript). When these events are triggered, you can then use a
custom function to do pretty much whatever you want with the event.
These custom functions are called Event Handlers.

The jQuery library provides methods to handle all the DOM events and
make complete event handling considerably easier than what we have
available in JavaScript.

Following are the examples of some common events −


1. A mouse click
2. A web page loading
3. Taking mouse over an element
4. Submitting an HTML form
5. A keystroke on your keyboard, etc.

126
What are jQuery Events?

127
What are jQuery Events?
jQuery Event Binding Syntax
Consider a situation when you want to click a <div> in an HTML document and then
you want to perform some action against this click. To achieve this you will have to
bind a jQuery click event with the <div> element and then define an action against
the click event.

Following is jQuery syntax to bind a click event with all the <div> elements available
in an HTML document:
$("div").click();

The next step is to define an action against the click event. Following is the syntax
to define a function which will be executed when click event will be fired. This
function is called jQuery Event Handler

$("div").click(function(){
// jQuery code goes here
}); 128
Mouse Events?

1. click: The click event is triggered when the user clicks on an element.
2. dblclick: The dblclick event is triggered when the user double-clicks on
an element.
3. mousedown: The mousedown event is triggered when the mouse
button is pressed down over an element.
4. mouseup: The mouseup event is triggered when the mouse button is
released after pressing it down over an element.
5. mouseover: The mouseover event is triggered when the mouse pointer
enters the boundaries of an element.
6. mouseout: The mouseout event is triggered when the mouse pointer
leaves the boundaries of an element.

129
Program : click event with <div> where an alert box is
displayed whenever you click on any of the divs.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("div").click(function(){
alert('Hi there!');
});
});

</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}
</style>
</head>
<body>
<p>Click on any of the squares to see the result:</p>

<div>One</div>
<div>Two</div>
<div>Three</div>
</body> </html> 130
Program : To demonstrate mouse events
<!DOCTYPE html>
<html>
<head>
<title>jQuery Combined Mouse Events</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="myDiv">Mouse over me and interact!</div>

<script>
$("#myDiv").click(function() {
alert("Click event triggered!");
});

$("#myDiv").dblclick(function() {
alert("Double-click event triggered!");
});

$("#myDiv").mousedown(function() {
alert("Mousedown event triggered!");
});

$("#myDiv").mouseup(function() {
alert("Mouseup event triggered!"); 131
});
To demonstrate mouse events

$("#myDiv").mouseover(function() {
$(this).css("background-color", "yellow");
alert("Mouseover event triggered!");
});

$("#myDiv").mouseout(function() {
$(this).css("background-color", "white");
alert("Mouseout event triggered!");
});
</script>
</body>
</html>

132
Form Events?

1. submit: The submit event is triggered when the user submits a form by clicking
a submit button or pressing Enter within an input field.
2. change: The change event is triggered when the value of a form element is
changed, typically used with input fields, checkboxes, and select elements.
3. input: The input event is triggered when the user enters or modifies the content
of an input field.
4. focus: The focus event is triggered when an input field or other form element
receives focus, i.e., the user clicks or tabs into the element.
5. blur: The blur event is triggered when an input field or other form element loses
focus, i.e., the user clicks or tabs out of the element.
6. reset: The reset event is triggered when the user clicks a reset button within a
form, which resets all form elements to their initial values.

133
Program : To demonstrate form events

<!DOCTYPE html>
<html>
<head>
<title>Combining Form Events</title>
</head>
<body>
<label for="username">Username:</label>
<input type="text" id="username" name="username"
oninput="showInputValue()"
onchange="showChangeValue()"
onfocus="showFocusMessage()"
onblur="showBlurMessage()">

<p id="inputValue"></p>
<p id="changeValue"></p>
<p id="focusMessage"></p>
<p id="blurMessage"></p>
134
<script>
function showInputValue( ) {
const inputValue = document.getElementById("username").value;
document.getElementById("inputValue").textContent = "Input value: " + inputValue;
}

function showChangeValue( ) {
const changeValue = document.getElementById("username").value;
document.getElementById("changeValue").textContent = "Change value: " + changeValue;
}

function showFocusMessage( ) {
document.getElementById("focusMessage").textContent = "Input focused!";
}

function showBlurMessage( ) {
document.getElementById("blurMessage").textContent = "Input lost focus!";
}
</script>
</body>
</html>

135
effects and animations Events?

jQuery provides a wide range of effects and animations that you can use
to enhance the interactivity and visual appeal of your web pages.

136
Form Events?

137
Ajax
• Ajax stands for "Asynchronous JavaScript and XML." It is a web
development technique that allows web pages to send and receive
data from a server asynchronously without requiring a full page reload.

• Ajax enables a smoother and more interactive user experience on web


applications.

138
Ajax
In the context of Ajax, the main difference between synchronous and
asynchronous requests lies in how the communication between the client (usually
a web browser) and the server takes place.

1. Synchronous Requests:
In synchronous requests, the client sends a request to the server and then
waits for the server to process the request and respond before the client can
proceed with other tasks.

During this waiting period, the browser typically freezes, and the user cannot
interact with the page until the server responds. Synchronous requests follow a
blocking behavior, where the browser is blocked until the server completes the
request.

1. Example of synchronous request using XMLHttpRequest in JavaScript:

139
Ajax
function makeSynchronousRequest( ) {
var xhr = new XMLHttpRequest( );
xhr.open('GET', 'https://api.example.com/data', false); // Third parameter "false"
// indicates synchronous request
xhr.send();

if (xhr.status === 200) {


console.log(xhr.responseText); // Process the response
}
else { OUTPUT:
console.error('Request failed: ' + xhr.status);
} [Response from the API]
} This line will be printed after the
synchronous request completes.
makeSynchronousRequest( );
console.log('This line will be printed after the synchronous request completes.');
140
Ajax
In the example above, the XMLHttpRequest is set to perform a synchronous GET
request to an API. The makeSynchronousRequest function waits for the response
from the server before printing the response or error message. During this waiting
period, the rest of the script execution is paused.

141
Ajax
Asynchronous Requests: In asynchronous requests, the client sends a request to
the server and continues executing other tasks without waiting for the server's
response.

When the server responds, the browser handles the response through a callback
function. This approach allows the browser to remain responsive, and the user can
continue interacting with the page while the request is being processed.

Example of asynchronous request using XMLHttpRequest in JavaScript:

142
Ajax
function makeAsynchronousRequest() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true); // Third parameter "true"
//indicates asynchronous request
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText); // Process the response
} else {
console.error('Request failed: ' + xhr.status);
} OUTPUT:
}
}; This line will be printed before the
xhr.send(); asynchronous request completes.
} [Response from the API]
makeAsynchronousRequest();
console.log('This line will be printed before the asynchronous request completes.');
143
Ajax
In this example, the XMLHttpRequest is set to perform an asynchronous GET
request to the API. The makeAsynchronousRequest function continues to execute
after sending the request without waiting for the response.

When the server responds, the onreadystatechange event is triggered, and the
appropriate action is taken based on the response state and status.

144
"onreadystatechange" event in an
XMLHttpRequest object.
1. The onreadystatechange event is a critical part of the XMLHttpRequest object
in JavaScript. It is used to monitor and handle changes in the state of an Ajax
request. When an XMLHttpRequest object makes a request to the server, its
state goes through several stages, and the onreadystatechange event is
triggered whenever the state changes.

2. The purpose of the onreadystatechange event is to allow developers to define


a callback function that will be executed each time the readyState property of
the XMLHttpRequest object changes. This callback function is where you can
handle the server's response and perform appropriate actions based on the
state of the request.

145
"onreadystatechange" event in an
XMLHttpRequest object.
function makeAjaxRequest(url, callback) {
var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// Request was successful, call the callback function with the response data
callback(null, xhr.responseText);
} else {
// Request failed, call the callback function with an error message
callback('Request failed with status: ' + xhr.status, null);
}
}
};
146
"onreadystatechange" event in an
XMLHttpRequest object.
xhr.open('GET', url, true);
xhr.send();
}

// Example usage:

var apiURL = 'https://api.example.com/data';

makeAjaxRequest(apiURL, function (error, response) {


if (error) {
console.error(error);
} else {
console.log('Response from server:', response);
// Process the response data here
}
}); 147
"onreadystatechange" event in an
XMLHttpRequest object.

In the example above, we define a function makeAjaxRequest that makes a GET


request to the specified url. Inside the onreadystatechange event listener, we
check if the readyState is 4, which means the request is complete. If the status is
200, the request was successful, and we call the callback function with the
response data. Otherwise, if the status is not 200, the request failed, and we call
the callback function with an error message.

1. By using the onreadystatechange event in this way, developers can efficiently


handle the server's response and take appropriate actions based on the
success or failure of the Ajax request.

148
GET and POST methods
GET Method: Fetching Data

The GET method is used to request data from a server. It is typically used to retrieve
data, and the data is sent in the URL as a query parameter. The GET method is safe,
meaning it should not have any side effects on the server or the data.

Example Program:

HTML:
<div id="output"></div>
<button id="fetch">Fetch Data</button>

149
GET methods
Reference:

In the HTML part, there are two elements: a <div> with the id
attribute set to "output" and a <button> with the id attribute set to
"fetch."
The purpose of the button is to trigger the AJAX request when
clicked, and the Fetch data will be displayed inside the <div>
element.

150
JavaScript :

$(document).ready(function() {
$("#fetch").click(function() {
// AJAX request using GET method
$.ajax({
url: "abc.com",
method: "GET",
success: function(data)
{
$("#output").text("Title: " + data.title);
},
error: function(error)
{
console.error("Error fetching data: " + error);
}
}); }); }); 151
GET methods
Reference:
1. In the JavaScript code, the $(document).ready() function

ensures that the code inside it is executed only when the


document (HTML) is fully loaded and ready.
2. Inside the $(document).ready() function, an event listener is

set up for the button with the id "fetch" using the .click()
method. When this button is clicked, the AJAX request will be
triggered.
3. The AJAX request is made using the $.ajax() method provided

by jQuery. It takes an object as its parameter, and this object


defines various settings for the AJAX request:
4. url: The URL to which the AJAX request is sent. In this case, it is

set to "abc.com." 152


GET methods
Reference:
5. method: The HTTP method used for the AJAX request. In this
case, it is set to "GET" to perform a GET request.
6. success: This is a callback function that will be executed if the
AJAX request is successful. Inside this function, the response data
from the server is accessed using the data parameter, and the
"title" property from the response data is used to update the text
content of the <div> element with the id "output."
7. error: This is a callback function that will be executed if the AJAX
request encounters an error. Inside this function, the error
message is printed to the console using console.error().

153
GET methods
EXAM:

To summarize, when the "Fetchdata" button is clicked, the


JavaScript code triggers an AJAX request to "abc.com" using the
GET method.

If the request is successful, the "title" property from the response


data is displayed inside the <div> element with the id "output."

If there is an error during the request, an error message is printed


to the console.

154
POST Method: Submitting Form
Data
• The POST method is used to submit data to a server.

• It is typically used when you want to send data to the server to create or update
resources. The data is sent in the request body, which is more secure and allows
for larger data payloads compared to the GET method.

155
Example Program:

HTML:

<form id="contactform">
<label for="name">Name:</label>
<input type="text" id="name" required>

<label for="message">Message:</label>

<textarea
id="message“required></textarea>

<button type="submit">Submit</button>

</form>
<div id="response"></div>

156
$(document).ready(function() {
$("#contactform").submit(function(event) {
event.preventDefault();

var name = $("#name").val();


var message = $("#message").val();

$.ajax({
url: "post.abc" ,
method: "POST",
data: {
title: name,
body: message,
},
success: function(data) {
$("#response").text("Data submitted successfully! Post ID: " + data.id);
},
error: function(error) {
$("#response").text("Error submitting data: " + error);
} }); }); }); 157
POST methods
EXAM:

The provided code makes an AJAX request to the server using the
POST method and sends the user-entered name and message in
the request body as JSON.
If the server successfully processes the request and responds with
a valid JSON object containing the id property, the success
message along with the post ID will be displayed in the "response"
<div>.
The success callback function is responsible for handling the
server's response in case of a successful request.
If there's an error, the error callback function is executed, and an
error message is logged to the console. 158
JSON

JSON stands for "JavaScript Object Notation." It is a lightweight data interchange


format that is easy for humans to read and write, and easy for machines to parse
and generate.

JSON is based on a subset of the JavaScript programming language and is often


used to transmit data between a server and a web application as an alternative to
XML.

159
JSON
JSON is commonly used in Ajax-based applications for several reasons:

1. Simplicity: JSON uses a simple and concise syntax, making it easy for
developers to work with and understand.
2. Lightweight: JSON has a smaller data overhead compared to XML, resulting in
faster data transmission and processing.
3. Native Support: JSON is natively supported in JavaScript, meaning that
JavaScript can easily parse JSON data using built-in methods like JSON.parse()
and convert JavaScript objects to JSON using JSON.stringify().
4. Language Agnostic: JSON is not limited to JavaScript and can be used with
many programming languages, making it a widely adopted data interchange
format.
5. Data Representation: JSON allows representing structured data with nested
objects and arrays, making it suitable for transmitting complex data structures.

160
JSON
JSON.parse( ) : This function is used to parse a JSON string and convert it into a
JavaScript object. It takes a valid JSON string as input and returns a
corresponding JavaScript object.

The example is as follows:

const jsonString = '{"name": "John", "age": 30, "isStudent": true}';


const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);

Output:
{ name: 'John', age: 30, isStudent: true }
161
JSON
JSON.stringify( ) : This function is used to convert a JavaScript object into a JSON
string representation. It takes a JavaScript object as input and returns a JSON
string.

Example :

const person = { name: 'John', age: 30, isStudent: true };


const jsonString = JSON.stringify(person);
console.log(jsonString);

Output:

'{"name":"John","age":30,"isStudent":true}'
162
JSON

1. The JSON object is enclosed in curly braces { }. It represents a collection of key-


value pairs.

2. Each key is a string (in double quotes) followed by a colon : to separate it from
its corresponding value.

1. The values can be of various types: strings, numbers, booleans (true or false),
objects (enclosed in their own curly braces), or arrays (enclosed in square
brackets []).

163
JSON
Example of a JSON object:
{
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"isSubscribed": true,
"address": {
"street": "123 Main St",
"city": "New York",
},
"hobbies": ["reading", "coding", "traveling"]
} 164
JSON
In the example above, we have a JSON object representing information about a
person. It contains various properties, such as "name," "age," "email," "isSubscribed,"
"address," and "hobbies." The "address" property is an embedded object, and the
"hobbies" property is an array of strings.

Processing a JSON object in JavaScript:

1. To process a JSON object in JavaScript, you can use the JSON.parse() method
to convert a JSON string into a JavaScript object, and JSON.stringify() to convert
a JavaScript object into a JSON string.

165
JSON
Example of parsing a JSON string:

var jsonString = '{"name":"John


Doe","age":30,"email":"[email protected]","isSubscribed":true}';
var personObj = JSON.parse(jsonString);
console.log(personObj.name); // Output: "John Doe"
console.log(personObj.age); // Output: 30
console.log(personObj.isSubscribed); // Output: true

166
JSON

Example of converting a JavaScript object to a JSON string:

var personObj = {
name: "John Doe",
age: 30,
email: "[email protected]",
isSubscribed: true,
};

var jsonString = JSON.stringify(personObj);


console.log(jsonString);
// Output: '{"name":"John
Doe","age":30,"email":"[email protected]","isSubscribed":true}'

167
JSON

In the examples above, we use JSON.parse( ) to convert the JSON string into a
JavaScript object and access its properties using dot notation. In the second
example, we use JSON.stringify( ) to convert the JavaScript object back to a JSON
string.

By using JSON, Ajax-based applications can easily exchange data with servers in a
standardized format that is efficient, easy to read, and compatible with multiple
programming languages.

168

You might also like