Unit II
Unit II
Unit II
JAVASCRIPT,
JQUERY and AJAX
JAVASCRIPT
What is JavaScript?
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.
• 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:
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.
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:
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
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'
};
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
}
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
38
Different Kinds of Loops
The do...while Loop
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".
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.
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...)
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.
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 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:
The href attribute with the value "#" is a relative URL that points to the
current page or simply represents a placeholder for a link.
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>
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:
<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.
• 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);
}
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
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.
63
JavaScript Arrays :
// Empty array
let emptyArray = [];
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.
65
JavaScript Arrays :
Modifying Elements: Elements within an array can be modified by
assigning new values using their index.
66
JavaScript Arrays :
Length Property: The length property of an array returns the number of
elements in the array.
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.
68
JavaScript Arrays :
Iterating over Arrays: Arrays can be iterated using loops like for, while, or
for...of.
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)
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.
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.
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.
79
getElementById :
In the above syntax:
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.
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.
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.
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.
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).
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.
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.
94
JavaScript Closures :
function greet(name)
{
var greeting = 'Hello';
function sayHello( )
{
console.log(greeting + name + '!');
}
return sayHello;
}
• When greet is called with the argument 'John', it returns the sayHello
function. The returned function is assigned to the variable
greetClosure.
• 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;
}
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.
• 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.
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.
100
What is jQuery?
101
What is jQuery?
102
Features of jQuery?
1. Here is the list of important core features supported by jQuery:
4. AJAX Support: The jQuery helps you a lot to develop a responsive and
feature-rich site using AJAX technology.
103
Features of jQuery?
104
How to use jQuery?
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.
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?
Example
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
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')
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
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,....')
Example
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.
$(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.
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.
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.
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();
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.
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.
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:
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
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
153
GET methods
EXAM:
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();
$.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
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.
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 :
Output:
'{"name":"John","age":30,"isStudent":true}'
162
JSON
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.
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:
166
JSON
var personObj = {
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