FSWDUNIT2

You might also like

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

FULL STACK WEB DEVELOPMENT

1. Script is a set of instruction used to perform certain task either on server side or client
side.
2. JavaScript is a subset of java.

Types of Scripting Languages


They are of 2 types (Client side Scripting Language and server side Scripting Language).
Javascript code is written in html page inside script tag. Client side script runs at client and
server side script runs at server.
Java Script Variables: It is a data name to store a data value. Example var a=10;
Initialization: Giving value to variable is called as Initialization. Example a=10;

<h2>Addition</h2><p id="result"></p> Addition


<p id="demotext">Change HTML content by JavaScript.</p> Sum=11
<script> var x =5, y = 6, z; z = x + y; Change
document.getElementById("result").innerHTML = "sum = " + z ;</script> HTML
<button type="button" content by
onclick='document.getElementById("demotext").innerHTML = "Hello JavaScript .
JavaScript!"'>Click Me!</button>

JavaScript Types
JavaScript Type Details
Internal JavaScript code is placed in the head and body section of an HTML
page.
External JavaScript codes are stored in separate external file using the .js
extension
(Ex: external.js).

Internal JavaScript Example


<script type="text/javascript"> document.write("Internal Javascript Example.");
</script>
Internal Javascript Example.

External JavaScript Example


external.js document.write("External Javascript Example."); External
abcd.html <script type="text/javascript" src="external.js"></script> Javascript
Example.

Printing in JavaScript
Method Writing into Example Program
innerHTML HTML <p id="demo"></p>
element <script>
document.write HTML output document.getElementById("demo").innerHTML = 5 +
() 6;
an alert box document.write(5 + 6);
window.alert() window.alert(5 + 6);
console.log(5 + 6);
</script>
<!—Print page 🡪
FULL STACK WEB DEVELOPMENT

console.log() browser <button onclick="window.print()">Click to Print the


console page</button>

Output 11 11

Java Script Operators


An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. Java Script is rich in built-in operators. Java script operator types were

1. Arithmetic. 2. Assignment. 3. Logical. 4. Comparison.


Expression C=a+b;
Operator +
Operands a,b, c

Arithmetic Operators
Operator Description Operator Description Operator Description
+ Addition / Division -- Decrement
- Subtraction % Modulus (Gives Remainder)
* Multiplication ++ Increment

Assignment Operators
Operator Description Same As Operator Description Same As
= x=y x=y *= x *= y x=x*y
+= x += y x=x+y /= x /= y x=x/y
-= x -= y x=x-y %= x %= y x=x%y

Logical Operators
Operator Description Output
&& logical and True / False based on condition
|| logical or True / False based on condition
! logical not True / False based on condition

Comparison Operators
Operator Description Output Operator Description Output
greater than or True /
== equal to True / False >=
equal to False
less than or True /
!= not equal to True / False <=
equal to False
ternary True /
> greater than True / False ?:
operator False
< less than True / False

Conditional Statements are of 4 types (If, Else, Else if and switch).They were
Conditional
Syntax Example Output
Statement
FULL STACK WEB DEVELOPMENT

if (condition) {
If if (3>2) { document.write("3 is big"); } 3 is big
Code }

if (condition) { if (2>3) { document.write("2 is big"); }


Else 3 is big
code } else { document.write("3 is big"); }
else { code }

if (condition1) if (2>3)
{ code } { document.write("2 is big"); }
Else if else if else if (3>2) { document.write("3 is big"); 3 is big
(condition2) }
{ code } else {document.write("Both are same");
else {code } }
switch(2)
switch(expression)
{
{
case 1: code
case 1: document.write("Selected
block; break;
Case2"); }; break;
switch case 1: code Selected Case2
case 2: document.write("Selected
block; break;
Case2"); }; break;
default: code
default:document.write("Selected Case
block; break;
Default"); }; break;
}
}

Statement Break & Continue


Statement Details
Break It is used to come out of a loop completely and continues executing the code
after the loop (if any).
Continue It breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

Java Script Looping Statements


It is a set of instructions which are repeated to perform a particular task with a certain
condition to save time, reduce errors and make code more readable.

While Loop
It is a set of Lines of code to be executed till it meets a certain condition. But I this loop first
checks the condition of the loop and then it enters into the code block. It the condition is
false it comes out of the loop.

Syntax Program Output


<script> 01234
var i = 0;
while (condition)
while (i < 5)
{ // code block to be executed }
{ document.writeln(i); i++; }
</script>
FULL STACK WEB DEVELOPMENT

The Do/While Loop


It is used to repeat a Block / Lines of code to be executed till it meets a certain condition.

Do/While Loop Syntax Program Output


<script>var i = 0; 01234
do {
do
document.writeln(i);
{ // Block / Lines of code to be executed
i++;
}
}
while (condition);
while (i < 5);
</script>

For Loop
It is used to repeat a Block / Lines of code to be executed till it meets a certain condition.
But in this loop first it enter into the code block and then increment / decrements the
counters and then checks the condition of the loop till the condition is false it comes out of
the loop.

For Loop Syntax Program Output


<script> var i = 0; 01234
for (Initialization; Condition; Increment /
for (i = 0; i < 5; i++)
Decrement)
{ document.writeln(i); }
{ // Block / Lines of code to be executed }
</script>

Types of JavaScript Comments


Comment Details
Type
Single-line It is represented by double forward slashes (//). It can be used before and
after the statement.
Multi-line It is represented by forward slash with asterisk then asterisk with
Comment forward slash. For example:/* your code here */

Functions
It is a set of instructions used to perform a particular task & function code is written inside
the script tag.

Program Output
No Arguments <script>
function hai() { window.alert("hi"); }
</script> hi in a window
<input type="button" value="click me"
onclick="hai();"/>
FULL STACK WEB DEVELOPMENT

Arguments <script>
function getcube(number){
alert(number*number*number);
}
</script> 64
<form>
<input type="button" value="click"
onclick="getcube(4)"/>
</form>
Return Value <script>
function Info(){
return "wisdom materials"; wisdom
} materials
document.write(Info());
</script>

JavaScript Object
It is a real world thing / entity having state and behavior (properties and method).
Example: car, pen, chair, glass, keyboard, monitor etc. JavaScript is an object-based
language. Everything is an object in JavaScript. Here we don't create class to get the
object. But, we direct create objects.

Creating Objects in JavaScript:


1. By object literal.
2. By creating instance of Object directly (using new keyword).
3. By using an object constructor (using new keyword).
Accessing Object Properties: objectName.propertyName (or)
objectName["propertyName"]

JavaScript Object by object literal


Syntax object={property1:value1,property2:value2.....propertyN:valueN}
Property and value is separated by: (colon).
Example <script>
var emp={id:2,name:" prasad ",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output 1 prasad 40000

By creating instance of Object


<script> 2 prasad 50000
var emp=new Object();
emp.id=2;
emp.name=" prasad ";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

By using an Object constructor


FULL STACK WEB DEVELOPMENT

We need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword. This keyword refers to the current object.
<script> 3 prasad 30000
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(3,"prasad",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>

JavaScript array
It is an object that represents a collection of similar type of elements. There are 2 ways to
construct array in JavaScript.
1. By array literal. 2. By creating instance of Array directly (using new keyword).

JavaScript array literal


Syntax Syntax: var arrayname=[value1,value2.....valueN];
The values are contained inside [ ] and separated by, (comma).
Example <h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = ["maruti", "mahindra", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
Output JavaScript Arrays
maruti, mahindra,BMW

JavaScript Array directly (new keyword)


Syntax var arrayname=new Array();
Here, new keyword is used to create instance of array.
Example <h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = new Array("maruti", "mahindra", "BMW");
document.getElementById("demo").innerHTML = cars;
</script>
Output JavaScript Arrays
maruti,mahindra,BMW

Access the Elements of an Array


Syntax We access an array element by referring to the index number.
var name = cars[0];
Example <h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes (starting
from 0).</p>
FULL STACK WEB DEVELOPMENT

<p id="demo"></p>
<script>
var cars = ["maruti", "mahindra", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
Output JavaScript Arrays: JavaScript array elements are accessed using numeric
indexes (starting from 0).
maruti

Changing an Array Element


Syntax This statement changes the value of the first element in cars: cars[0]
= "Opel";
Example <h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accessed using numeric indexes</p>
<p id="demo"></p>
<script>
var cars = ["maruti", "mahindra", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars;
</script>
Output JavaScript Arrays
JavaScript array elements are accessed using numeric indexes
Opel,mahindra,BMW

Array Properties and Methods


Syntax var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays
The length Property:
The length property of an array returns the length of an array (the number of
array elements).
Example <p>The length property returns the length of an array.</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length;
</script>
Output The length property returns the length of an array. 4

Associative Arrays
Syntax Arrays with named indexes are called associative arrays (or hashes). JavaScript
support arrays with numbered indexes but not named indexes.
Example <h2>JavaScript Associative Arrays</h2>
<p id="demo"></p>
<script>
var person = [];
person[0] = "prasad";
person[1] = "wisdom";
person[2] = 46;
document.getElementById("demo").innerHTML =
FULL STACK WEB DEVELOPMENT

person[0] + " " + person.length;


</script>
Output JavaScript Associative Arrays: prasad 3

JavaScript array constructor (new keyword)


Syntax We need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.
Example <script>
var emp=new Array("wisdom","materials","prasad");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
} </script>
Output Wisdom materials prasad

JavaScript Array Methods


Array Method Example
toString() var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML =
fruits.toString();
Result : Banana,Orange,Apple,Mango
join() var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join("
* ");
Result: Banana * Orange * Apple * Mango
pop() removes last var fruits = ["Banana", "Orange", "Apple", "Mango"];
element fruits.pop();
window.alert(fruits);
Result: Banana,Orange,Apple
push() method add new var fruits = ["Banana", "Orange", "Apple", "Mango"];
element fruits.push("Kiwi");
window.alert(fruits);
Result: Banana,Orange,Apple, Mango, Kiwi
shift() removes first var fruits = ["Banana", "Orange", "Apple", "Mango"];
element and shifts all fruits.shift();
other elements to a window.alert(fruits);
lower index. Result: Orange,Apple,Mango
concat() Arrays var alpha = ["a", "b"];
var numer = [1, 2, 3];
var alphanumer = alpha.concat(numer);
document.getElementById("demo").innerHTML =
alphanumer;
window.alert(alphanumer);
Result: a,b,1,2,3
slice() slices array into a var fruits =
new array ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(2);
window.alert(citrus);
Result: Lemon,Apple,Mango
FULL STACK WEB DEVELOPMENT

JavaScript String
The JavaScript string is an object that represents a sequence of characters. Create string in
2 way uisng JavaScript.
1. By string literal. 2. By string object using new keyword

Syntax By string literal: It is created using double quotes.


syntax: var stringname="string value";
Example <script>
var str="wisdom materials is a string";
document.write(str);
</script>
Output wisdom materials is a string

2) By string object using new keyword


Syntax var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Example <script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Output hello javascript string

JavaScript String Methods


String Methods Details
charAt() Provides the char value present at the specified index.
charCodeAt() Provides the Unicode value of a character present at the specified
index.
concat() provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
search() It searches a specified regular expression in a given string and
returns its position if a match occurs.
match() It searches a specified regular expression in a given string and
returns that regular expression if a match occurs.
replace() replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the
specified starting position and length.
substring() It is used to fetch the part of the given string on the basis of the
specified index.
slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index
toLowerCase() Converts the given string into lowercase letter.
toLocaleLowerCase( Converts the given string into lowercase letter on the basis of host?s
) current locale.
toUpperCase() Converts the given string into uppercase letter.
FULL STACK WEB DEVELOPMENT

toLocaleUpperCase( It converts the given string into uppercase letter on the basis of
) host?s current locale.
toString() Provides a string representing the particular object.
valueOf() Provides the primitive value of string object.
split() Splits a string into substring array, then returns that newly created
array.
trim() trims the white space from the left and right side of the string.

Example
Program Output
<script> S
//charAt(index) Method
var str="wisdom materials";
document.write(str.charAt(2)+ "<br>");

//JavaScript String concat(str) Method


var s1="concat "; concat example
var s2="example";
var s3=s1+s2;
document.write(s3+"<br>");

//String indexOf(str) Method


var s4="javascript from wisdom materials"; 11
var n=s4.indexOf("from"); 23
document.write(n+"<br>"); wisdom
WISDOM MATERIALS
//String lastIndexOf(str) Method wisdommat
var s5="javascript from wisdom materials"; wisdom materials
var n=s5.lastIndexOf("materials");
document.write(n+"<br>");

//toLowerCase() Method
var s6="WISDOM";
document.write(s6.toLowerCase()+"<br>");

//toLowerCase() Method
var s7="wisdom materials";
document.write(s7.toUpperCase()+"<br>");

//String slice(beginIndex, endIndex) Method


var s8="wisdommaterials";
var s9=s8.slice(0,9);
document.write(s9+"<br>");

//String trim() Method


var s10=" wisdom materials ";
document.write(s10.trim());
</script>
FULL STACK WEB DEVELOPMENT

JavaScript Date Object


It is used to get year, month and day, hour, minute and seconds displayed on the webpage.

JavaScript Date Object Constructors


Date() Date(milliseconds)
Date(dateString) Date(year, month, day, hours, minutes, seconds, milliseconds)

JavaScript Date Methods


Function Returns integer value between
getDate() 1 and 31 that represents the day for the specified date on the basis of
local time
getDay() 0 and 6 that represents the day of the week on the basis of local time
getFullYears() that represents the year on the basis of local time
getHours() 0 and 23 that represents the hours on the basis of local time.
getMilliseconds( 0 and 999 that represents the milliseconds on the basis of local time
)
getMinutes() 0 and 59 that represents the minutes on the basis of local time
getMonth() 0 and 11 that represents the month on the basis of local time
getSeconds() 0 and 60 that represents the seconds on the basis of local time.

Example
Program Output
Current Date and Time: Current Date and Time:
<p id="txt"></p> Tue Jan 30 2024 14:29:31 GMT+0530
<script> (India Standard Time)
var today=new Date();
document.getElementById('txt').innerHTML=toda
y;
</script>
JavaScript Methods
<script> Date:25
var d = new Date("2021-03-25") FullYear:2021
document.write("Date:"+d.getDate()+"<br>"); Month:2
document.write("FullYear:"+d.getFullYear()+"<br Hours:5
>"); Minutes:30
document.write("Month:"+d.getMonth()+"<br>") Seconds:0
;
document.write("Hours:"+d.getHours()+"<br>");
document.write("Minutes:"+d.getMinutes()+"<br
>");
document.write("Seconds:"+d.getSeconds()+"<br
>");
</script>

JavaScript Math
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.

JavaScript Math Methods


FULL STACK WEB DEVELOPMENT

Methods returns
abs() Absolute value of the given number.
acos() arccosine of the given number in radians
asin() Arcsine of the given number in radians.
atan() arc-tangent of the given number in radians
cbrt() cube root of the given number
ceil() a smallest integer value, greater than or equal to the given number.
cos() Cosine of the given number.
cosh() Hyperbolic cosine of the given number.
exp() exponential form of the given number
floor() Largest integer value, lower than or equal to the given number.
hypot() square root of sum of the squares of given numbers
log() Natural logarithm of a number.
max() Maximum value of the given numbers.
min() Minimum value of the given numbers.
pow() Value of base to the power of exponent.
random() random number between 0 (inclusive) and 1 (exclusive)
round() closest integer value of the given number
sign() the sign of the given number
sin() sine of the given number
sinh() Hyperbolic sine of the given number.
sqrt() square root of the given number
tan() Tangent of the given number.
tanh() Hyperbolic tangent of the given number.
trunc() An integer part of the given number.

JavaScript Number Object


It enables you to represent a numeric value (integer / floating-point.) As floating-point
numbers.
Number() constructor used to create number object in JavaScript.
var n=new Number(value);
If value can't be converted to number, it returns NaN(Not a Number) that can be checked
by isNaN() method.
Program <script>
var x=119;//integer value
var y=119.9;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object
document.write(x+" "+y+" "+z+" "+n);
</script>
Output 119 119.9 130000 16

JavaScript Number Constants


JavaScript Number Constants Returns The
MIN_VALUE largest minimum value
MAX_VALUE largest maximum value
POSITIVE_INFINITY positive infinity, overflow value
NEGATIVE_INFINITY infinity, overflow value
FULL STACK WEB DEVELOPMENT

Nan Represents "Not a Number" value.

JavaScript Number Methods


Method Return/Convert/determine Details
s
isFinite() determines Whether the given value is a finite number.
isInteger() Whether the given value is an integer.
parseFloat() converts String into a floating point number.
parseInt() Converts a String into an integer number.
toExponential Returns a String represents exponential notation of the
() given number.
toFixed() Returns a String (represents a number with exact digits
after a decimal point).
toPrecision() Returns a String (represents a number with exact digits
after a decimal point).
toString() Returns a Number in the form of string.

JavaScript Boolean
Theory JavaScript Boolean is an object that represents value in two states: true or false.
You can create the JavaScript Boolean object by Boolean() constructor.
Boolean b=new Boolean(value);
The default value of JavaScript Boolean object is false.
Exampl <script>
e document.write(10<20);//true
document.write(10<5);//false
</script>

JavaScript Boolean Properties


Constructor: returns the reference of Boolean function that created Boolean object.
Prototype: enables you to add properties and methods in Boolean prototype.

JavaScript Boolean Methods:


toSource():returns the source of Boolean object as a string.
toString():converts Boolean into String.
valueOf():converts other type into Boolean.
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the
execution. This process of reacting over the events is called Event Handling. Thus, js
handles the HTML events via Event Handlers. Mouse events, Keyboard events, Form
events, Window/Document events.

addEventListener() method.
Progra <p> addEventListener() method </p>
m <button id = "btn"> Click me </button>
<p id = "para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
FULL STACK WEB DEVELOPMENT

function fun() {
document.getElementById("para").innerHTML = "Hi Wisdom materials";
}
</script>
Output Hi Wisdom materials

JavaScript onclick event


It occurs when the user clicks on an element. It allows the programmer to execute a
JavaScript's function when an element gets clicked. This event can be used for validating a
form, warning messages and many more.

Progra <p> onclick method demo</p>


m <input type="button" name="Click me" value="Click me" onclick="fun()"/>
<script>
function fun() { alert("Welcome to wisdom materials"); }
</script>
Output Welcome to wisdom materials
Progra <p id="para"> onclick method demo</p>
m <input type="button" name="Click me" value="Click me" onclick="fun()"/>
<script>
function fun() {
document.getElementById("para").innerHTML = " Welcome to wisdom
materials ";
document.getElementById("para").style.color = "blue";
document.getElementById("para").style.backgroundColor = "yellow";
document.getElementById("para").style.fontSize = "25px";
document.getElementById("para").style.border = "4px solid red";
}
</script>
Output Welcome to wisdom materials

JavaScript Form Validation


JavaScript is used to validate (validate name, password, email, date, mobile numbers e.tc
fields) the form on the client-side so data processing will be faster than server-side
validation.

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


function Validate()
{
var t1=document.f1.t1.value;
if (t1.length < 8) { alert('Please enter details in textbox1'); return false; }
else { alert(t1); return true; }
}
</script>
<body>
TextBox
<form name="f1" onsubmit="return Validate()" action="http://www.google.com/"
method="post" >
Username
FULL STACK WEB DEVELOPMENT

<input type="text" name="t1" id="fname" />


<input type="reset" value="reset" name="reset" />
<input type="submit" value="submit" name="submit" />
</form>
</body>

Radio
<script>
function tv()
{
var tbv=document.f1.g.value;
alert("Text Validation fucntion");

if(tbv=="male" || tbv=="female" )
alert("true");
else
alert("false / Choose a proper gender");
}
</script>

<form name="f1">
male<input type="radio" name="g" value="male" /><br>
female<input type="radio" name="g" value="female"
/><br>

<input type="reset" name="b" value="reset" />


<input type="button" name="b" value="click me"
onclick="tv()" />

</form>

Select
<script>
function tv()
{
var tbv=document.f1.country.value;
alert(tbv);

if(tbv==0)
{ alert("Choose a Country / False"); return False; }

else
{ alert(tbv); return true; }
FULL STACK WEB DEVELOPMENT

}
</script>

<form name="f1" " onsubmit="return tv()"


action="https://www.google.com/" method="get" >
<select name="country">
<option value="0">Select country</option>
<option value="India">India</option>
<option value="china">china</option>
<option value="us">us</option>
<option value="uk">uk</option>
</select>

<input type="reset" name="b" value="reset" />


<input type="submit" name="b" value="click me" />

</form>

Gmail
<script language="javascript" type="text/javascript">
function Validate()
{
var t1 = document.f1.t4.value;
if (t1.match("@gmail.com"))
{alert(t1); return true;}
else
{
alert("Enter a proper Gmail");
return false;
}
}
</script>

Gmail Validation<br>
<form name="f1" onsubmit="return Validate()" action="http://www.google.com/"
method="post" >
Email : <input type="text" name="t4" id="email2"/><br>
<input type="reset" value="reset" name="reset" />
<input type="submit" value="submit" name="submit" />
</form>

AJAX (Asynchronous JavaScript and XML)


It is not a programming language ". It is not exactly a client-side technology, nor a
server-side technology: It's both! Ajax is a technique in which websites use JavaScript
FULL STACK WEB DEVELOPMENT

(client-side) to send data to, and retrieve data from, a server-side script. This all happens in
the background so data can be updated on the current page without requiring the user to
load a new page. AJAX use text or JSON text to transport data but not XML.

Example
Ajax.html <div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
ajax_info.tx <h1>AJAX</h1>
t <p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>
FULL STACK WEB DEVELOPMENT

1. An event occurs in a web page (the page is loaded, a button is clicked)


2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

The XMLHttpRequest Object


It isused to exchange data with a server. This means that it is possible to update parts of a
web page, without reloading the whole page.

Access across Domains


1. The web page and the XML file it tries to load, must be located on the same server.
2. If you want to use the example above on one of your own web pages, the XML files you
load must be located on your own server.

XMLHttpRequest Object Methods


Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method,url,async,user,ps Specifies the request
w) method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests
FULL STACK WEB DEVELOPMENT

send(string) Sends the request to the server.


Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties


Property Description
onreadystatechan Defines a function to be called when the readyState property
ge changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")

AJAX - Server Response


The readyState property holds the status of the XMLHttpRequest.
The onreadystatechange property defines a function to be executed when the readyState
changes. The status property and the statusText property holds the status of the
XMLHttpRequest object.

Property Description
onreadystatechange Defines a function to be called when the readyState property
changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized, 1: server connection established, 2: request
received, 3: processing request, 4: request finished and response is
ready
status 200: "OK", 403: "Forbidden", 404: "Page not found", For a
complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")

AJAX XML Example


AJAX can be used for interactive communication with an XML file.
Program <style>
Ajaxxml.html table,th,td {border : 1px solid black; border-collapse: collapse;}
</style>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Get my CD
collection</button><br><br>
FULL STACK WEB DEVELOPMENT

<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
cd_catalog.xm <?xml version="1.0" encoding="UTF-8"?>
l <CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>
FULL STACK WEB DEVELOPMENT

AJAX PHP Example


AJAX is used to create more interactive applications.
Program <h1>The XMLHttpRequest Object</h1>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "gethint.php?q="+str, true);
xhttp.send();
}
</script>
gethint.ph <?php
p // Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL


$q = $_REQUEST["q"];
FULL STACK WEB DEVELOPMENT

$hint = "";

// lookup all hints from array if $q is different from ""


if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}

// Output "no suggestion" if no hint was found or output correct values


echo $hint === "" ? "no suggestion" : $hint;
?>
Output

Code explanation
First, check if the input field is empty (str.length == 0). If it is, clear the content of the
txtHint placeholder and exit the function. However, if the input field is not empty, do the
following:

Create an XMLHttpRequest object


Create the function to be executed when the server response is ready
Send the request off to a PHP file (gethint.php) on the server
Notice that q parameter is added gethint.php?q="+str
The str variable holds the content of the input field

Program <!DOCTYPE html>


Ajaxdb.html <html>
<style>
table,th,td { border : 1px solid black; border-collapse: collapse;}
th,td { padding: 5px;}
</style>
<body>
FULL STACK WEB DEVELOPMENT

<h1>The XMLHttpRequest Object</h1>


<form action="">
<select name="customers" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>

<script>
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
</script>
</body>
</html>
getcustomer.ph AJAX Database Example
p AJAX can be used for interactive communication with a database.

<?php
$mysqli = new mysqli("servername", "username", "password",
"dbname");
if($mysqli->connect_error) {
exit('Could not connect');
}

$sql = "SELECT customerid, companyname, contactname, address, city,


postalcode, country
FROM customers WHERE customerid = ?";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
FULL STACK WEB DEVELOPMENT

$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();

echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo "<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname . "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" . $adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" . $pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country . "</td>";
echo "</tr>";
echo "</table>";
?>
Output

jQuery
Jquery Jquery is JavaScript library, Subset of java, free, open-source software and
lightweight, "write less, and do more".
Developed by John Resig at BarCamp NYC in January 2006
jQuery HTML manipulation, DOM manipulation, DOM element selection, CSS
Features manipulation, Effects and Animations, Utilities, AJAX, HTML event
methods, JSON Parsing, Extensibility through plugins
Used by Google, Microsoft, IBM, Netflix
Applications Show & Hide P tag, Fade, SlideDown and Slideup, Animation, Chaining
etc.
FULL STACK WEB DEVELOPMENT

syntax Show and Hide P tag


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></sc
ript>

<script type="text/javascript">
$(document).ready(function () {
$("#hide").click(function () { $("div").hide(); });
$("#show").click(function () { $("div").show(); });
});
</script>

<div>Click buttons to show / hide text</div>


<button id="hide">Hide</button>
<button id="show">Show</button>

jQuery Selectors
jQuery selectors use factory function ($()) find / select HTML elements based on their id,
classes, attributes, types and much more from a DOM. $()= factory function uses the three
basic building blocks while selecting an element in a given document.

Selector Description
Tag It represents a tag name available in the DOM. Example: $('p') selects all
Name paragraphs'p'in the document.
It represents a tag available with a specific ID in the DOM. Example:
Tag ID $('#real-id') selects a specific element in the document that has an ID of real-id.
Tag It represents a tag available with a specific class in the DOM. Example:
Class: $('real-class') selects all elements in the document that have a class of real-class.

Selector: ITag Name, Tag ID and Tag Class


FULL STACK WEB DEVELOPMENT

<script src=" jquery.min.js"></script>


<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
</script>
<p id="test">Selecting element by its Id example hidden
</p>
<button>Click me</button><br><br><br><br>

<script>
$(document).ready(function(){
$("h2").click(function(){
$(".test1").hide();
});
});
</script>
<b class="test1">class selector example hidden</b>
<h2>click Class Selector </h2><br><br><br><br>

<script>
$(document).ready(function(){
$("pre").click(function(){
$("i").css("background-color", "red");
});
});
</script>
<i>Element Selector example hidden</i>
<pre>Click me to pre tag to hide </pre>

How to use Selectors


S.No
. Selector It selects
1 Name: all elements that match with the given element name.
2 #ID: a single element that matches with the given id.
3 .Class: all elements that matches with the given class.
4 Universal(*) all elements available in a DOM.
the combined results of all the specified selectors A,B and
5 Multiple Elements A,B,C C.

Selector
Selector Example It will select
* $("*") all elements.
#id $("#firstname") element with id="firstname"
.class $(".primary") all elements with class="primary"
FULL STACK WEB DEVELOPMENT

$(".primary,.secondary all elements with the class "primary" or


class,.class ") "secondary"
element $("p") all p elements.
el1,el2,el3 $("h1,div,p") all h1, div, and p elements.
:first $("p:first") first p element
:last $("p:last") last p element
:even $("tr:even") all even tr elements
:odd $("tr:odd") all odd tr elements
all p elements that are the first child of their
:first-child $("p:first-child") parent
all p elements that are the first p element of
:first-of-type $("p:first-of-type") their parent
all p elements that are the last child of their
:last-child $("p:last-child") parent
all p elements that are the last p element of
$("p:last-of-type") their parent
all p elements that are the 2nd child of their
:nth-child(n) $("p:nth-child(2)") parent
all p elements that are the 2nd child of their
:nth-last-child(n) $("p:nth-last-child(2)") parent, counting from the last child
all p elements that are the 2nd p element of
:nth-of-type(n) $("p:nth-of-type(2)") their parent
:nth-last-of-type( $("p:nth-last-of-type(2) all p elements that are the 2nd p element of
n) ") their parent, counting from the last child
all p elements that are the only child of their
:only-child $("p:only-child") parent
all p elements that are the only child, of its
:only-of-type $("p:only-of-type") type, of their parent
all p elements that are a direct child of a div
parent > child $("div > p") element
parent all p elements that are descendants of a div
descendant $("div p") element
element + next $("div + p") p element that are next to each div elements
element ~ all p elements that are siblings of a div
siblings $("div ~ p") element
:eq(index) $("ul li:eq(3)") fourth element in a list (index starts at 0)
the list elements with an index greater than
:gt(no) $("ul li:gt(3)") 3
:lt(no) $("ul li:lt(3)") the list elements with an index less than 3
:not(selector) $("input:not(:empty)") all input elements that are not empty
:header $(":header") all header elements h1, h2 ...
:animated $(":animated") all animated elements
:focus $(":focus") the element that currently has focus
:contains(text) $(":contains('Hello')") all elements which contains the text "Hello"
:has(selector) $("div:has(p)") all div elements that have a p element
:empty $(":empty") all elements that are empty
FULL STACK WEB DEVELOPMENT

all elements that are a parent of another


:parent $(":parent") element
:hidden $("p:hidden") all hidden p elements
:visible $("table:visible") all visible tables
:root $(":root") It will select the document's root element
all p elements with a lang attribute value
:lang(language) $("p:lang(de)") starting with "de"
[attribute] $("[href]") all elements with a href attribute
$("[href='default.htm'] all elements with a href attribute value
[attribute=value] ") equal to "default.htm"
[attribute!=value $("[href!='default.htm'] all elements with a href attribute value not
] ") equal to "default.htm"
[attribute$=valu all elements with a href attribute value
e] $("[href$='.jpg']") ending with ".jpg"
all elements with a title attribute value
[attribute|=value $("[title|='Tomorrow']" equal to 'Tomorrow', or starting with
] ) 'Tomorrow' followed by a hyphen
[attribute^=valu all elements with a title attribute value
e] $("[title^='Tom']") starting with "Tom"
[attribute~=valu all elements with a title attribute value
e] $("[title~='hello']") containing the specific word "hello"
[attribute*=valu all elements with a title attribute value
e] $("[title*='hello']") containing the word "hello"
:input $(":input") all input elements
:text $(":text") all input elements with type="text"
:password $(":password") all input elements with type="password"
:radio $(":radio") all input elements with type="radio"
:checkbox $(":checkbox") all input elements with type="checkbox"
:submit $(":submit") all input elements with type="submit"
:reset $(":reset") all input elements with type="reset"
:button $(":button") all input elements with type="button"
:image $(":image") all input elements with type="image"
:file $(":file") all input elements with type="file"
:enabled $(":enabled") all enabled input elements
:disabled $(":disabled") all disabled input elements
:selected $(":selected") all selected input elements
:checked $(":checked") all checked input elements

jQuery Events
All the different visitors' actions that a web page can respond to are called events. Events
examples: A mouse click, An HTML form submission, A web page loading, A keystroke on
the keyboard, Scrolling of the web page etc.

These events can be categorized on the basis their types:


Mouse Events Keyboard Events Window Events Form Events
FULL STACK WEB DEVELOPMENT

Click(), Dblclick(), Keyup() , Load() , Unload(), Submit(),


Mouseenter() , Keydown() Scroll(), Resize() hange(),
Mouseleave(), hover() ,Keypress() Blur() , Focus()

Commonly Used jQuery Event Methods:


The $(document).ready() method allows us to execute a function when the document is fully
loaded.click():The click() method attaches an event handler function to an HTML element.
Events
mouseenter Mouseenter & mouseleave
<script src=" <script src=" jquery.min.js"></script>
jquery.min.js"></script> <script>
<script> $(document).ready(function(){
$(document).ready(function(){ $("p").on({
$("#p1").mouseenter(function(){ mouseenter: function(){
alert("You entered p1!"); $(this).css("background-color", "lightgray");
}); },
}); mouseleave: function(){
</script> $(this).css("background-color", "lightblue");
<p id="p1">Mouseenter },
function</p> click: function(){
$(this).css("background-color", "yellow");
}
});
});
</script>
<p>mouseenter & mouseleave function on P
tag.</p>
The on() Method: The on() method attaches one or
more event handlers for the selected elements.
Use mouseleave, mousedown, mouseup, hover, dblclick(),Click() In place of mouseenter.

Form Events
focus blur
<script src=" jquery.min.js"></script> <script src=" jquery.min.js"></script>
<script> <script>
$(document).ready(function(){ $(document).ready(function(){
$("input").focus(function(){ $("input").focus(function(){
$(this).css("background-color", $(this).css("background-color", "yellow");
"yellow"); });
}); $("input").blur(function(){
$("input").blur(function(){ $(this).css("background-color", "green");
$(this).css("background-color", });
"green"); });
}); </script>
}); Name: <input type="text"
</script> name="fullname"><br>
Name: <input type="text" Email: <input type="text" name="email">
name="fullname"><br>
FULL STACK WEB DEVELOPMENT

Email: <input type="text"


name="email">
change() Submit function()
<script src=" jquery.min.js"></script> <script src=" jquery.min.js"></script>
<script> <script>
$(document).ready(function(){ $(document).ready(function(){
$("input").change(function(){ $("form").submit(function(){
alert("text change Function."); alert("Submit function");
}); });
}); });
</script> </script>
<input type="text"> </head>
<p>Enter text and press outside (text <body>
change Function)</p> <form action="about.html">
Name: <input type="text"
name="FirstName" value="Mickey"><br>
Salary: <input type="text" name="Salary"
value="99999"><br>
<input type="submit" value="Submit">
</form>

Example: When a click event fires on a <p> element; hide the current <p> element:
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});
});
</script>
<p>Click or move the mouse pointer over this paragraph.</p>
Output Change paragraph background color on mouse hover.

JQuery DOM Manipulation


It provides methods to select and manipulate DOM elements. JQuery provides methods
such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM
FULL STACK WEB DEVELOPMENT

elements. Content Manipulation: The html( ) method gets the html contents (innerHTML)
of the first matched element. Syntax: selector.html()

Examples
DOM To Add Elements DOM to Replace Elements
<script src=" jquery.min.js"> <script src=" jquery.min.js"></script>
</script> <script>
<script> $(document).ready(function()
$(document).ready(function() { {
$("div").click(function () { $("div").click(function () {
var content = $(this).html(); $(this).replaceWith("content replaced JQuery is
$("#result").text( content ); Great");
}); }); }); });
</script> </script>
<span id = "result"> </span> <span id = "result"> </span>
<div id = "division">Click to replace div
<div id = "division">Click to Add content</div>
content</div>
Click to Add content content replaced JQuery is Great
Click to Add content
Removing DOM Elements selector.remove([expr]) or selector.empty()
The empty( ) method remove all child nodes from
the set of matched elements where as the
method remove( expr ) method removes all
matched elements from the DOM.
<script>
$(document).ready(function()
{
$("div").click(function ()
{
$(this).remove( );
}); });
</script>
<style>div{ margin:10px;padding:12px;
border:2px solid #666; width:30px;} </style>
<p>Click on any square below:</p>
<span id = "result"> </span>
<div class = "div" style =
"background-color:blue;"></div>
<div class = "div" style =
"background-color:green;"></div>
<div class = "div" style =
"background-color:red;"></div>

JQuery Effects:
With jQuery,we can hide and show HTML elements with the hide() and show() methods.
FULL STACK WEB DEVELOPMENT

Syntax: $(selector).hide(speed,callback); $(selector).show(speed,callback);

<script src=" jquery.min.js"></script> Show function


<script> Hide function
$(document).ready(function(){
$("b").click(function(){ Hide / show
$("p").hide();
});
});

$(document).ready(function(){
$("div").click(function(){
$("p").show();
});
});
</script>
<div>Show function</div>
<b>Hide function</b>
<p>Hide / show</p>
jQuery toggle between hiding and showing an element
toggle(): with the toggle() method.
Syntax:$(selector).toggle(speed,callback);
speed parameter take values:”slow”,”fast”,or
milliseconds. callback parameter is a function
to be executed after toggle() completes.
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
<button>Toggle between hiding and showing
the paragraphs</button>
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
jQuery Fading Methods:
With jQuery you can fade an element in and out of visibility.
Jquery has the following fade methods: fadeIn(), Fadeout(), fadeToggle(), fadeTo()
$(selector).fadeIn(speed,callback);

Program Output
FULL STACK WEB DEVELOPMENT

<script src=" jquery.min.js"></script>


<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
<p>Demonstrate fadeIn() with different parameters.</p>
<button>Click to fade in boxes</button><br><br>
<div id="div1"
style="width:80px;height:80px;display:none;background-color:r
ed;"></div><br>
<div id="div2"
style="width:80px;height:80px;display:none;background-color:g
reen;"></div>

jQuery Sliding Methods:With jQuery you can create a sliding effect on elements.
jQuery has the following slide methods: slideDown(), slideUp(), slideToggle()
Syntax :$(selector).slideDown(speed,callback); - speed - milliseconds

Program Output
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});

$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideUp("slow");
});
});
</script>
<style>
#panel, #flip {padding: 5px;text-align: center;
background-color: #e5eecc;border: solid 1px #c3c3c3;}
#panel {padding: 50px;display: none;}
</style>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
FULL STACK WEB DEVELOPMENT

jQuery Animations
The Jquery animate() method is used to create custom animations.
Syntax :$(selector).animate({params},speed,callback);
params Defines the CSS properties to be animated.
speed Milliseconds.
callback It is a function to be executed after the animation completes.

Examples
Start Animation(Click to move Rect) Output
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '250px'});
});
});
</script>
<button>Start Animation(Click to move Rect)</button><br>
<div style="background:#98bf21;height:100px;
width:100px;position:absolute;"></div>

Program
Start Animation(Click to move Rect) Output
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
});
</script>
<button>Start Animation by changing multiple properties of
Rect</button>
<div
style="background:#98bf21;height:100px;width:100px;position:absol
ute;"></div>
jQuery animate() - Using Relative Values: Output
It is done by putting += or -= in front of the values:
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
FULL STACK WEB DEVELOPMENT

left: '250px',
height: '+=150px',
width: '+=150px'
});
});
});
</script>
<button>Start Animation using relative values</button>
<div style="background:#98bf21;height:100px;
width:100px;position:absolute;"></div>
jQuery animate() - Using Pre-defined Values: Output
We can even specify a properties animation values as “show”,,”hide”,
or “toggle”:
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
height: 'toggle'
});
});
});
</script>
<button>Start Animation</button>
<div style="background:#98bf21;height:100px;
width:100px;position:absolute;"></div>
Uses Queue Functionality Output
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "slow");
});
});
</script>
<button>Start Animation</button>
<div
style="background:#98bf21;height:100px;width:100px;position:absol
ute;"></div>
Start Animation to change font size Output
FULL STACK WEB DEVELOPMENT

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({left: '100px'}, "slow");
div.animate({fontSize: '3em'}, "slow");
});
});
</script>
<button>Start Animation to change font size</button>
<div
style="background:#98bf21;height:100px;width:200px;position:absol
ute;">HELLO</div>

stop() : The jQuery stop() method is used to stop an animation or effect before it is finished.
The stop() method works for all jQuery effects functions,including sliding,fading and
custom animations.
Syntax:$(selector).stop(stopAll,goToEnd);
stopAll parameter specifies whether also the animation queue should be cleared or not.
Default is false, which means that only the active animation will be stopped, allowing any
queued animations to be performed afterwards. goToEnd parameter specifies whether or
not to complete the current animation immediately. Default is false.

Program to stop expanding the div tag Output


<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
</script>
<style>
#panel, #flip {
padding: 5px;font-size: 18px;text-align: center;
background-color: #555;color: white;border: solid 1px
#666;
border-radius: 3px;}
#panel {padding: 50px;display: none;}
</style>
<button id="stop">Stop sliding</button>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
FULL STACK WEB DEVELOPMENT

jQuery Method Chaining:


chaining technique allows us to run multiple jQuery commands, one after the other, on the
same element(s). To chain an action, you simply append the action to the previous action.
Chain together css(),slideUp(),and slideDown(). P tag changes to red, slides up, and slides
down.

Program to scroll the p tag Output


<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
});
});
</script>
<p id="p1">jQuery is fun!!</p>
<button>Click me</button>
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000);
});
});
</script>
<p id="p1">jQuery is fun!!</p>
<button>Click me</button>

jQuery Traversing
jQuery traversing, which means "move through", are used to "find" (or select) HTML
elements based on their relation to other elements. Start with one selection and move
through that selection until you reach the elements you desire. The image below illustrates
an HTML page as a tree (DOM tree). With jQuery traversing, you can easily move up
(ancestors), down (descendants) and sideways (siblings) in the tree, starting from the
selected (current) element. This movement is called traversing - or moving through - the
DOM tree.

The <div> element is the parent of <ul>, and an ancestor of everything inside of it
FULL STACK WEB DEVELOPMENT

The <ul> element is the parent of both <li> elements, and a child of <div>
The left <li> element is the parent of <span>, child of <ul> and a descendant of <div>
The <span> element is a child of the left <li> and a descendant of <ul> and <div>
The two <li> elements are siblings (they share the same parent)
The right <li> element is the parent of <b>, child of <ul> and a descendant of <div>
The <b> element is a child of the right <li> and a descendant of <ul> and <div>
Traversing the DOM:
jQuery provides a variety of methods that allow us to traverse the DOM.
The largest category of traversal methods are tree-traversal.

jQuery Traversing - Ancestors


With jQuery you can traverse up the DOM tree to find ancestors of an element.An ancestor
is a parent, grandparent, great-grandparent, and so on.

Jquery methods for traversing up the DOM tree:


Parent(), Parents(), parentsUntil(). jQuery parent() Method returns the direct parent
element of the selected element.This method only traverse a single level up the DOM tree.
Program
<style>
.ancestors * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parent().css({"color": "red", "border": "2px solid red"});
});
</script>
<div class="ancestors">
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent)
<li>li (direct parent)
<span>span</span>
</li>
</ul>
</div>
<div style="width:500px;">div (grandparent)
<p>p (direct parent)
<span>span</span>
</p>
</div>
</div>
FULL STACK WEB DEVELOPMENT

All parents
<style>
.ancestors * { display: block;border: 2px solid lightgrey;color: lightgrey;
padding: 5px;margin: 15px;}</style>
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parents().css({"color": "red", "border": "2px solid red"});
});
</script>

<body class="ancestors">body (great-great-grandparent)


<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent)
<li>li (direct parent)
<span>span</span>
</li>
</ul>
</div>
</body>

jQuery parentsUntil() Method:


The parentsUntil() method returns all anscetor elements between two given arguments.
<style>
.ancestors * {
display: block;border: 2px solid lightgrey;
color: lightgrey;padding: 5px;margin: 15px;}
</style>
<script src=" jquery.min.js"></script>
<script>
FULL STACK WEB DEVELOPMENT

$(document).ready(function(){
$("span").parentsUntil("div").css({"color": "red", "border": "2px solid red"});
});
</script>
<body class="ancestors"> body (great-great-grandparent)
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent)
<li>li (direct parent)
<span>span</span>
</li>
</ul>
</div>
</body>

jQuery Traversing - Descendants


With jQuery you can traverse down the DOM tree to find descendants of an element.
A descendant is a child, grandchild, great-grandchild, and so on. jQuery methods for
Traversing Down the DOM Tree: Children(), Find(), jQuery children() Method:
The children() method returns all direct children of the selected element.
This method only traverses a single level down the DOM tree.

<style> .descendants * { display: block;border: 2px solid lightgrey;color:


lightgrey;padding:
5px;margin: 15px;}</style>

<script src=" jquery.min.js"></script>


<script>
$(document).ready(function(){
$("div").children().css({"color": "red", "border": "2px solid red"});
});
</script>
<body>
<div class="descendants" style="width:500px;">div (current element)
<p>p (child) <span>span (grandchild)</span> </p>
<p>p (child) <span>span (grandchild)</span> </p>
</div>
</body>
FULL STACK WEB DEVELOPMENT

jQuery find() Method:


It returns descendant elements of the selected element,all the way down to the last
descendant.
<style>.descendants * { display: block;border: 2px solid lightgrey;color: lightgrey;
padding: 5px;margin: 15px;}</style>
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").find("span").css({"color": "red", "border": "2px solid red"});
});
</script>

<body>
<div class="descendants" style="width:500px;">div (current element)
<p>p (child) <span>span (grandchild)</span> </p>
<p>p (child) <span>span (grandchild)</span> </p>
</div>
</body>

jQuery Traversing - Siblings


With jQuery you can traverse sideways in the DOM tree to find siblings of an element.
Siblings share the same parent. The siblings() method returns all sibling elements of the
selected element. jQuery methods for Traversing Sideways in The DOM Tree:
Siblings(), Next(), nextAll(), nextUntil(), Prev(), prevAll(), prevUntil()
FULL STACK WEB DEVELOPMENT

<style>.siblings * { display: block;border: 2px solid lightgrey;


color: lightgrey;padding: 5px;margin: 15px;}</style>
<script src=" jquery.min.js"></script>

<script>
$(document).ready(function(){
$("h2").siblings().css({"color": "red", "border": "2px solid
red"});
});
</script>
</head>
<body class="siblings">
<div>div (parent)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div>
</body>

jQuery next() Method:


It returns the next sibling element of the selected element.

<style>.siblings * { display: block; border: 2px solid lightgrey;


color: lightgrey; padding: 5px; margin: 15px;}</style>
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("h2").next().css({"color": "red", "border": "2px solid red"});
});
</script>
<body class="siblings">
<div>div (parent)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div>
</body>

jQuery nextUntil() Method


It returns all next sibling elements between two given arguments.
FULL STACK WEB DEVELOPMENT

<style>.siblings * { display: block; border: 2px solid lightgrey;


color: lightgrey; padding: 5px; margin: 15px;}</style>
<script src=" jquery.min.js"></script>

<script>
$(document).ready(function(){
$("h2").nextUntil("h6").css({"color": "red", "border": "2px
solid red"});
});
</script>
<body class="siblings">
<div>div (parent)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<h4>h4</h4>
<h5>h5</h5>
<h6>h6</h6>
<p>p</p>
</div>
</body>

jQuery nextAll() Method


It returns all next sibling elements of the selected element.
<style>.siblings * { display: block; border: 2px solid lightgrey;
color: lightgrey; padding: 5px; margin: 15px;}</style>
<script src=" jquery.min.js"></script>

<script>
$(document).ready(function(){
$("h2").nextAll().css({"color": "red", "border": "2px solid red"});
});
</script>
<body class="siblings">
<div>div (parent)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div>
</body>

jQuery Traversing - Filtering


Filtering methods: first(),last() and eq(). which allow we select a specific element based on
its position in a group of elements.

jQuery first() Method: It returns the first element of the specified elements.
FULL STACK WEB DEVELOPMENT

<script src=" jquery.min.js"></script>


<script>
$(document).ready(function(){
$("div").first().css("background-color",
"orange");
});
</script>

<body>
<h1>My Homepage</h1>
<p>Paragraph.</p>
<div style="border: 1px solid black;">
<p>Paragraph1 in div.</p>
<p>Paragraph2 in div.</p>
</div><br>

<div style="border: 1px solid black;">


<p>Paragraph3 in div.</p>
<p>Paragraph4 in div.</p>
</div><br>

<div style="border: 1px solid black;">


<p>Paragraph5 in div.</p>
<p>Paragraph6 in div.</p>
</div>
</body>
jQuery last() Method:
The last() method returns the last element of the
specified elements.In place of first() use last().

jQuery eq() method


It returns an element with a specific index number of the selected elements.
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").eq(0).css("background-color", "yellow");
$("p").eq(3).css("background-color", "orange");
});
</script>
<body>
<p>Paragraph1</p> <p>Paragraph2</p>
<p>Paragraph3</p> <p>Paragraph4</p>
</body>
FULL STACK WEB DEVELOPMENT

jQuery filter() Method:


It specify a criteria. Elements that do not match the criteria are removed from the
selection,and those that match will be returned.

<script src=" jquery.min.js"></script>


<script>
$(document).ready(function(){
$("p").filter(".abcd1234").css("background-color", "yellow");
});
</script>
<body>
<h1>heading</h1>
<p>Paragraph11</p>
<p class="abcd1234">Paragraph2</p>
<p class="abcd1234">Paragraph3</p>
<p>Paragraph4</p>
</body>

jQuery not() Method


It returns all elements that do not match the criteria. The not() method is the opposite of
filter().
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").not(".abcd1234").css("background-color", "yellow");
});
</script>
<body>
<h1>heading</h1>
<p>Paragraph11</p>
<p class="abcd1234">Paragraph2</p>
<p class="abcd1234">Paragraph3</p>
<p>Paragraph4</p>
</body>

You might also like