0% found this document useful (0 votes)
1 views136 pages

JavaScript

JavaScript is a lightweight, object-oriented programming language primarily used for creating interactive web pages. It allows for dynamic content without reloading the page and is supported by all major web browsers. JavaScript features include weak typing, prototype-based inheritance, and the ability to manipulate HTML elements and handle events.

Uploaded by

Sai Srinivas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views136 pages

JavaScript

JavaScript is a lightweight, object-oriented programming language primarily used for creating interactive web pages. It allows for dynamic content without reloading the page and is supported by all major web browsers. JavaScript features include weak typing, prototype-based inheritance, and the ability to manipulate HTML elements and handle events.

Uploaded by

Sai Srinivas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 136

High Level Programming

What is JavaScript?

JavaScript (js) is a light-weight object-oriented scripting and programming language which


is used by several websites for scripting the WebPages. It is an interpreted, full-fledged
programming language that enables dynamic interactivity on websites when applied to an HTML
document. It was introduced in the year 1995 for adding programs to the webpages in the
Netscape Navigator browser. Since then, it has been adopted by all other graphical web
browsers. With JavaScript, users can build modern web applications to interact directly without
reloading the page every time. The traditional website uses js to provide several forms of
interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In addition
to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their scripting
and query language.

Features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution
environments.

2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.

3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending
on the operation).

4. JavaScript is an object-oriented programming language that uses prototypes rather than


using classes for inheritance.

5. It is a light-weighted and interpreted language.

6. It is a case-sensitive language.

7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.

8. It provides good control to the users over the web browsers.


Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
o Displaying clocks etc.

Where to insert

In HTML, JavaScript code is inserted between <script> and </script> tags.

JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

External file:

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:

<html>

<head>

<script src=”abc.js”>

</script>
</head>

</html>

abc.js

document.write("Hello JavaScript ");

JavaScript Output

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML
content:

<body>

<h1 id="myTitle">Original Title</h1>

<button onclick="changeTitle()">Change Title</button>

<script>
function changeTitle() {

document.getElementById("myTitle").innerHTML = "New Title!";

</script>

</body>

Using document.write()

<body>

<h2>My First Web Page</h2>

<p>My first paragraph.</p>

<p>Never call document.write after the document has finished loading.

It will overwrite the whole document.</p>

<script>

document.write("hello");

</script>

</body>
Example2;

<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" onclick="document.write(“my first javascript”)>Try it</button>

</body>

Using window.alert()

You can use an alert box to display data:

<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(“hello”); //alert(“hello”);
</script>

</body>

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display
data.

JavaScript Print

JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the browser to print
the content of the current window.
<body>

<button onclick="window.print()">Print this page</button>

</body>

Window prompt()

The prompt() method displays a dialog box that prompts the user for input.

A prompt box is used if you want the user to input a value.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed.

<body>

<script>

var x = prompt(“enter value for x”);

var y = prompt(“enter value for y”); ;

var z=x+y;

document.write(z);

</script>

</body>
JavaScript Example:
<html>

<body>

<h2>Welcome to JavaScript</h2>

<script>

document.write("Hello JavaScript by JavaScript");

</script>

</body>

</html>

Output: Welcome to JavaScript

Hello JavaScript by JavaScript

JavaScript Variable

A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript: local variable and global variable. There are some rules while declaring a JavaScript
variable (also known as identifiers).
Identifiers can be short names (like x and y) or more descriptive names (age, sum, total Volume).

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names
 JavaScript identifiers are case-sensitive.

Declaring (Creating) JavaScript Variables:

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var keyword:

var carName;

Correct JavaScript variables:

1. var x = 10;
2. var _value="sonoo";

Incorrect JavaScript variables:

1. var 123=30;
2. var *aa=320;

Example of JavaScript variable:

<html>

<body>

<script>

var x = 10;
var y = 20;

var z=x+y;

document.write(z);

</script>

</body>

</html>

Output:30

i) JavaScript local variable:

A JavaScript local variable is declared inside block or function. It is accessible within the
function or block only.

1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>

Or,

1. <script>
2. If(10<13){
3. var y=20;//JavaScript local variable
4. }
5. </script>

ii) JavaScript global variable:

A JavaScript global variable is accessible from any function. A variable i.e. declared outside
the function or declared with window object is known as global variable.

Example:
<html>

<body>

<script>

var data=200;//global variable

function a(){

document.writeln(data);

function b(){

document.writeln(data);

a();//calling JavaScript function

b();

</script>

</body>

</html>

Output: 200 200

JavaScript Arrays

JavaScript arrays are used to store multiple values in a single variable.

What is an Array?

An array is a special variable, which can hold more than one value at a time.

var car1 = "Saab";


var car2 = "Volvo";
var car3 = "BMW";

i) Creating an Array:
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:var array name = [item1, item2, ...];

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p id="demo"></p>

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body></html>

Output:

JavaScript Arrays

Saab,Volvo,BMW

Spaces and line breaks are not important. A declaration can span multiple lines:

Example:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Arrays</h2>

<p id="demo"></p>

<script>

var cars = [

"Saab",
"Volvo",

"BMW"

];

document.getElementById("demo").innerHTML = cars;

</script>

</body>

</html>

Output: JavaScript Arrays

Saab,Volvo,BMW

ii) Using the JavaScript Keyword new:

The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.

Example:

<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Output:
Arun
Varun
John

iii) Access the Elements of an Array:

You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

var name = cars[0];

iv) JavaScript array constructor (new keyword):

To create instance of array by passing arguments in constructor so that we don't have to provide
value explicitly.

The example of creating object by array constructor is given below.

<html>

<body>

<script>

var emp=new Array("Jai","Vijay","Smith");

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

</script>

</body>
</html>

Output: Jai
Vijay
Smith

JavaScript Array Methods:


Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the modified array.

entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided function
conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively till the specified
depth.

flatMap() It maps all array elements via mapping function, then flattens the result into a new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided function conditions.

find() It returns the value of the first element in the given array that satisfies the specified condition.

findIndex() It returns the index value of the first element in the given array that satisfies the specified
condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then loops through these
keys.

lastIndexOf() It searches the specified element in the given array and returns the index of the last match.

map() It calls the specified function for every array element and returns the new array

of() It creates a new array from a variable number of arguments, holding any type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and reduces the array to a single
JavaScript Objects

A javaScript object is an entity having state and behavior (properties and method). For example:
car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.JavaScript is


template based not class based. Here, we don't create class to get the object. But, we direct create
objects.

Creating Objects in JavaScript:

There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal: syntax of creating object using object literal is

object={property1:value1,property2:value2.....propertyN:valueN}
property and value is separated by : (colon).
Example:
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Output: 102 Shyam Kumar 40000

Object Properties:

The name: values pairs in JavaScript objects are called properties:


Example: Property Property Value

1. age 50

2.firstName John

Accessing Object Properties: You can access object properties in two ways:

objectName.propertyName / objectName["propertyName"]

2) By creating instance of Object:

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

example of

<html>

<body>

<script>

var emp=new Object();

emp.id=101;

emp.name="Ravi Malik";

emp.salary=50000;

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

</body>

</html>
Output: 101 Ravi Malik 50000

3) By using an Object constructor:

Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.The this keyword refers to the current object.

In a function definition, this refers to the "owner" of the function.

Example:

<html>

<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

</script>

</body>

</html>

Output: 103 Vimal Jaiswal 30000

Defining method in JavaScript Object:


Objects can also have methods.Methods are actions that can be performed on objects.Methods
are stored in properties as function definitions.But before defining method, we need to add
property in the function with same name as method.

Accessing Object Methods:


Syntax: objectName.methodName()
Example:

<html>

<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

this.changeSalary=changeSalary;

function changeSalary(otherSalary){

this.salary=otherSalary;

e=new emp(103,"Sonoo Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

e.changeSalary(45000);

document.write("<br>"+e.id+" "+e.name+" "+e.salary);

</script>

</body>

</html>
Output: 103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

JavaScript Objects:

Document

Arrays

Math objects

String objects

Date Objects

The HTML DOM Document Object

DOM:When a web page is loaded, the browser creates a Document Object Model of the
page.

The document object represents your web page.

If you want to access any element in an HTML page, you always start with accessing the
document object.

Finding HTML Elements


Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id.

var myElement = document.getElementById("intro");

Example:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML DOM</h2>

<p id="intro">Finding HTML Elements by Id</p>

<p >This example demonstrates the <b>getElementsById</b> method.</p>

<p id="demo"></p>

<script>

var element = document.getElementById("intro");


document.getElementById("demo").innerHTML =

"The text from the intro paragraph is: " + element.innerHTML;

</script>

</body>

</html>

If the element is found, the method will return the element as an object (in myElement).

If the element is not found, myElement will contain null.

Finding HTML Elements by Tag Name

var x = document.getElementsByTagName("p");

This example finds all <p> elements:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Tag Name.</p>

<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>

<p id="demo"></p>
<script>

Var element = document.getElementsByTagName("p");

document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: ' +


element[0].innerHTML;

</script>

</body>

</html>

Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name, use
getElementsByClassName().

This example returns a list of all elements with class="intro".

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Class Name.</p>


<p class="intro">Hello World!</p>

<p class="intro">This example demonstrates the <b>getElementsByClassName</b>


method.</p>

<p id="demo"></p>

<script>

const x = document.getElementsByClassName("intro");

document.getElementById("demo").innerHTML =

'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;

</script>

</body>

</html>

DOM manipulation

The below list contains different methods to manipulate DOM.

Table of Content

 DOM Element Selectors


 DOM content manipulators
 DOM element creators
 DOM CSS manipulators

DOM Element Selectors

There are multiple methods available in DOM to select the HTML elements and
manipulate them as listed below:
 querySelector() method: A query selector is a method used in JavaScript to select
and manipulate elements in the Document Object Model (DOM). It allows you to
retrieve elements from an HTML document using CSS selectors.

 querySelectorAll() method: The querySelectorAll() method returns a NodeList


which contains all elements that match the selector within the document.

 getElementById( ) method: The getElementId() method is used to select a single


element using its Id.

 getElementByClassName( ): The getElementsByClassName()


method in JavaScript is used to select elements in the HTML document that have a
specific class name.

 getElementByTagName() method: The getElementsByTagName() method is used to


select elements using the specified tag name.

 getElementByName() method: The getElementsByName() method is used to select


elements that have a specific name attribute. This method returns a NodeList of
elements with the specified name

<!DOCTYPE html>

<html>

<head>

<title>

GeeksForGeeks

</title>

</head>

<body style="text-align: center;">

<div id="target">
<h1>Hello Geeks</h1>

<h2 class="example">

This is a sample sub heading

</h2>

<p>

This is sample paragraph1

</p>

<p>

This is sample paragraph2

</p>

<input type="text" name="username"

id="userName">

</div>

<script>

const queryS =

document.querySelector(".example");

const gebi =

document.getElementById("target");

const gebcn =

document.getElementsByClassName('example');

const gebtn =

document.getElementsByTagName('p');
const gebn =

document.getElementsByName('username');

const querySAll =

document.querySelectorAll("p");

console.log(queryS);

console.log(gebi);

console.log(gebcn);

console.log(gebn);

console.log(gebtn);

console.log(querySAll);

</script>

</body>

DOM content manipulators

The below DOM properties can be used to change the HTML and the text content of
the HTML elements.

 textContent: The textContent property is used to set and get the text content and it's
descendants.

 innerHTML: The innerHTML property is used to get and set the text
and HTML inside an HTML element.

 innerText: The innerText property represents the rendered text content of a node
and its descendants. It is aware of the elements which will be rendered and ignores
the hidden elements.

<!DOCTYPE html>

<html>
<head>

<title>

DOM Manipulation Techniques

</title>

DOM element creators

You can also create dynamic HTML elements using the below DOM methods.

 createElement( ) method: The createElement( ) method is used to create an element


in the HTML DOM document

 appendChild( ) method: The appendChild( ) method is used to append a node to a


list of child nodes of a specified parent node.

 createTextNode( ) method: The createTextNode( ) method is used to create a text


node

<!DOCTYPE html>

<html>

<head>

<title>

DOM Manipulation Techniques

</title>

</head>

<body style="text-align: center;">


<h1>Hello 1</h1>

<h2>Hello 2</h2>

<h3>Hello 3</h3>

<script>

const para =

document.createElement("p");

para.textContent =

"This paragraph is created using createElement!";

const para1 =

document.createTextNode("p");

para1.textContent =

"This paragraph is created using createTextNode";

document.body.appendChild(para);

document.body.appendChild(para1);

</script>

</body>

</html>

DOM CSS manipulators


The below DOM properties can be used to manipulate the CSS of the HTML elements.

 style: CSS can be manipulated using (Syntax : element.style.propertyName) which


helps us to dynamically manipulate styles and access the inline styles of an element.

 cssText: CSS can be directly manipulated using the cssText property of the style
object to set multiple inline styles at a time. It is similar to how we add inline CSS to
an element.

 classList: As Inline CSS is not recommended, mostly we use classList property to


dynamically add and remove CSS classes which are defined in external CSS.

<!DOCTYPE html>

<html>

<head>

<title>

DOM Manipulation Techniques

</title>

<style>

.classList {

color: white;

background-color: black;

text-align: center

</style>

</head>
<body>

<h1>Hello 1</h1>

<h2>Hello 2</h2>

<h3>Hello 3</h3>

<script>

const tcontentexample =

document.querySelector("h1");

const innerhtmlexample =

document.querySelector("h2");

const innertextexample =

document.querySelector("h3");

tcontentexample.style.

color = "white";

tcontentexample.style.

backgroundColor = "black";

tcontentexample.style.

textAlign = "center";

innerhtmlexample.style.cssText =

`color: white;

background-color: black;

text-align:center`;

innertextexample.classList.add("classList");
</script>

</body>

</html>

S.N Methods Description


o

1 Object.assign() This method is used to copy enumerable and own properties from a
source object to a target object

2 Object.create() This method is used to create a new object with the specified prototype
object and properties.

3 Object.defineProperty() This method is used to describe some behavioral attributes of the


property.

4 Object.defineProperties() This method is used to create or configure multiple object properties.

5 Object.entries() This method returns an array with arrays of the key, value pairs.

6 Object.freeze() This method prevents existing properties from being removed.

7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the specified property of
the specified object.

8 Object.getOwnPropertyDescriptors() This method returns all own property descriptors of a given object.

9 Object.getOwnPropertyNames() This method returns an array of all properties (enumerable or not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all own symbol key properties.

11 Object.getPrototypeOf() This method returns the prototype of the specified object.


12 Object.is() This method determines whether two values are the same value.

13 Object.isExtensible() This method determines if an object is extensible

14 Object.isFrozen() This method determines if an object was frozen.

15 Object.isSealed() This method determines if an object is sealed.

16 Object.keys() This method returns an array of a given object's own property names.

17 Object.preventExtensions() This method is used to prevent any extensions of an object.

18 Object.seal() This method prevents new properties from being added and marks all
existing properties as non-configurable.

19 Object.setPrototypeOf() This method sets the prototype of a specified object to another object.

20 Object.values() This method returns an array of values.

JavaScript Math Object

The math object provides the properties and methods for mathematical constants and

functions. Unlike the other global objects, Math is not a constructor. All properties and

methods of Math are static and can be called by using Math as an object without creating it.

varpi_val = Math.PI; //Math object need not be created

varsine_val = Math.sin(30)

Math Properties

Property Description

E Euler's constant and the base of natural logarithms, approximately2.718.

LN2 Natural logarithm of 2, approximately 0.693.

LN10 Natural logarithm of 10, approximately 2.302.

LOG2E Base 2 logarithm of E, approximately 1.442.

LOG10E Base 10 logarithm of E, approximately 0.434.


PI Ratio of the circumference of a circle to its diameter, approximately

3.14159.

SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2,

approximately 0.707.

SQRT2 Square root of 2, approximately 1.414.

Math Methods

Method Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

asin() Returns the arcsine (in radians) of a number.

atan() Returns the arctangent (in radians) of a number.

atan2() Returns the arctangent of the quotient of its arguments.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns the cosine of a number.

exp() Returns EN, where N is the argument, and E is Euler's constant,the

base of the natural logarithm.

floor( ) Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

abs() Returns the absolute value of a number.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is, base exponent.

random() Returns a pseudo

round() Returns the value of a number rounded to the nearest integer.

sin() Returns the sine of a number.


sqrt() Returns the square root of a number.

tan() Returns the tangent of a number.

Eg: document.writeln(math.pi);

JavaScript String object:

Varval = new String(string);

String Methods

Method Description

String() Returns the string object.

charAt(i) Returns the character at the specified index

charCodeAt(index) Returns a number indicating the Unicode value of the character

at the given index.

concat() Combines the text of two strings and returns the combined string.

indexOf() Returns the index of the first occurrence of the String object of

or -1 if not found.

lastIndexOf() Returns the index within the calling String object of the last

occurrence of the specified valu match() Used to match a regular expression against a string.

replace() Used to find a match between a regular expression and a string,

and to replace the matched substring with a new substring

search() Executes the search for a match between a regular expression

and a specified string.

slice() Extracts a section of a string and returns a new string.

split() Splits a String object into an array of strings by separating the

string into substrings.

substr() Returns the characters in a string beginning at the specified

location through the specified number of characters.


substring() Returns the characters in a string between two indexes into the

string.

toLowerCase() Returns the calling string value converted to lower case.

toString() Returns a string representing the specified object.

toUpperCase() Returns the calling string value converted to uppercase.e, or -1 if not found.

JavaScript Date Object

The Date object is a data type built into the JavaScript language. Once a Date object is created, a number
of methods are available to operate onit.

new Date( ) - This constructor creates a Date object set to the current date and time.

new Date(milliseconds)- When one numeric argument is passed, it is taken as the internal numeric
representation of the date in milliseconds, as returned bythe getTime( ) method

new Date(year,month,date[,hour,minute,second,millisecond ]) -The parameters on square brackets are


optional

Date Methods
Method Description
Date() Returns today's date and time
getDate() Returns the day of the month for the specified date
accordingto local time.
getDay() Returns the day of the week for the specified date according
tolocal time.
getFullYear() Returns the year of the specified date according to local time.
getHours() Returns the hour in the specified date according to local time.
getMilliseconds() Returns the milliseconds in the specified date according to
local time.
getMinutes() Returns the minutes in the specified date according to local
time.
getMonth() Returns the month in the specified date according to local
time

setDate() Sets the day of the month for a specified date according to

local time.

setFullYear() Sets the full year for a specified date according to local time.

setHours() Sets the hours for a specified date according to local time.

setMilliseconds() Sets the milliseconds for a specified date according to local

time.

setMinutes() Sets the minutes for a specified date according to local time.

setMonth() Sets the month for a specified date according to local time.

setSeconds() Sets the seconds for a specified date according to local time.

setTime() Sets the Date object to the time represented by a number of

milliseconds since January 1, 1970, 00:00:00 UTCset methods


JavaScript Loops

The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

1) JavaScript For loop:

The JavaScript for loop iterates the elements for the fixed number of times. It should be
used if number of iteration is known.

syntax: for (initialization; condition; increment)


{
code to be executed
}

Example:

<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>

Output:
1
2
3
4
5
2) JavaScript while loop: The JavaScript while loop iterates the elements for the infinite
number of times. It should be used if number of iteration is not known.

syntax : while (condition)


{
code to be executed
}

Example:

<!DOCTYPE html>

<html>

<body>

<script>

var i=11;

while (i<=15)

document.write(i + "<br/>");

i++;

</script>

</body>

</html>

output:

11
12
13
14
15

3) JavaScript do while loop:

The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false.

syntax: do{

code to be executed
}while (condition);

Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
Output:
21
22
23
24
25

4) JavaScript for in loop:


The JavaScript for in loop is used to iterate the properties of an object.

Conditionals

Conditional statements are used to perform different actions based on different conditions.

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

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

i) JavaScript If statement: It evaluates the content only if expression is true.


Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Output:

<html>

<body>

<script>

var a=20;

if(a>10){

document.write("value of a is greater than 10");

</script>

</body>

</html>

output: value of a is greater than 10


ii)JavaScript If...else Statement: It evaluates the content whether condition is true of false.

Syntax:

1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }

Example:
<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>
output: a is even number

iii)JavaScript If...else if statement:

It evaluates the content only if expression is true from several expressions.

Syntax:

1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10. else{
11. //content to be evaluated if no expression is true
12. }

Example:

<html>

<body>

<script>

var a=20;

if(a==10){

document.write("a is equal to 10");

else if(a==15){

document.write("a is equal to 15");

else if(a==20){

document.write("a is equal to 20");

else{

document.write("a is not equal to 10, 15 or 20");

</script>
</body>

</html>

Output: a is equal to 20

JavaScript Switch Statement


The JavaScript switch statement is used to execute one code from multiple expressions.

Use the switch statement to select one of many code blocks to be executed.

Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.

Example:

<!DOCTYPE html>

<html>

<body>

<script>

var grade='B';
var result;

switch(grade){

case 'A':

result="A Grade";

break;

case 'B':

result="B Grade";

break;

case 'C':

result="C Grade";

break;

default:

result="No Grade";

document.write(result);

</script>

</body>

</html>

output: B Grade

The break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
The switch statement is fall-through i.e. all the cases will be evaluated if you don't use break
statement.

Example:

<!DOCTYPE html>

<html>

<body>

<script>

var grade='B';

var result;

switch(grade){

case 'A':

result+=" A Grade";

case 'B':

result+=" B Grade";

case 'C':

result+=" C Grade";

default:

result+=" No Grade";

document.write(result);

</script>

</body>

</html>
output: undefined B Grade C Grade No Grade

JavaScript Functions

JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.

Advantage of JavaScript function:

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code
each time to perform a common task.

JavaScript Function Syntax:

A JavaScript function is defined with the function keyword, followed by a name,


followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


// code to be executed
}

Function parameters are listed inside the parentheses () in the function


definition.Function arguments are the values received by the function when it is
invoked.Inside the function, the arguments (the parameters) behave as local variables.

Example: <html>

<body>

<script>

function msg(){
alert("hello! this is message");

</script>

<input type="button" onclick="msg()" value="call function"/>

</body>

</html>

output:
call function

Function Invocation:

The code inside the function will execute when "something" invokes (calls) the function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

JavaScript Function Arguments: We can call function by passing arguments.


Example: <html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>

Function with Return Value:We can call function that returns a value and use it in our
program.

<html>
<body>

<script>

function getInfo(){

return "hello javatpoint! How r u?";

</script>

<script>

document.write(getInfo());

</script>

</body>

</html>

output: hello javatpoint! How r u?

JavaScript Function Object:

In JavaScript, the purpose of Function constructor is to create a new Function object. It


executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.

Syntax:

new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter

arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

JavaScript Function Methods:

Method Description
apply() It is used to call a function contains this value and a single array of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

Example:

<!DOCTYPE html>

<html>

<body>

<script>

var add=new Function("num1","num2","return num1+num2");

document.writeln(add(2,5));

</script>

</body>

</html>

output:7

Predefined functions:

Isfinite()

isNan()

ParseInt()

parseFloat()
Eval()

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.

For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.

 When a user clicks the mouse


 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key.

Mouse events:

Event Performed Event Handler Description

Click Onclick When mouse click on an element

Mouseover Onmouseover When the cursor of the mouse comes over the element
Mouseout Onmouseout When the cursor of the mouse leaves an element

Mousedown Onmousedown When the mouse button is pressed over the element

Mouseup Onmouseup When the mouse button is released over the element

Mousemove Onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:

Event Performed Event Handler Description

Focus Onfocus When the user focuses on an element

Submit Onsubmit When the user submits the form

Blur Onblur When the focus is away from a form element

Change Onchange When the user modifies or changes the value of a form elem

Window/Document events:

Event Performed Event Handler Description

Load Onload When the browser finishes the loading of the page

Unload onunload When the visitor leaves the current webpage, the browser unlo

Resize Onresize When the visitor resizes the window of the browser
Click Event:

<html>

<head> Javascript Events </head>

<body>

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

function clickevent()

document.write("This is JavaTpoint");

</script>

<form>

<input type="button" onclick="clickevent()" value="Who's this?"/>

</form>

</body>

</html>

Keydown Event:

<html>

<head> Javascript Events</head>

<body>

<h2> Enter something here</h2>


<input type="text" id="input1" onkeydown="keydownevent()"/>

<script>

function keydownevent()

document.getElementById("input1");

alert("Pressed a key");

</script>

</body>

</html>

Load event:

<html>

<head>Javascript Events</head>

</br>

<body onload="window.alert('Page successfully loaded');">

<script>

document.write("The page is loaded successfully");

</script></body></html>
Form Validating

It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.

Example: In this example, we are going to validate the name and password. The name can’t be
empty and password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.

<html>

<body>

<script>

function validateform(){

var name=document.myform.name.value;

var password=document.myform.password.value;

if (name==null || name==""){

alert("Name can't be blank");

return false;

}else if(password.length<6){

alert("Password must be at least 6 characters long.");

return false;

}
}

</script>

<body>

<form name="myform" method="post"


action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()"
>

Name: <input type="text" name="name"><br/>

Password: <input type="password" name="password"><br/>

<input type="submit" value="register">

</form>

</body>

</html>

JavaScript Retype Password Validation:

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">

function matchpass(){

var firstpassword=document.f1.password.value;

var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){

return true;

}
else{

alert("password must be same!");

return false;

</script>

</head>

<body>

<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp"


onsubmit="return matchpass()">

Password:<input type="password" name="password" /><br/>

Re-enter Password:<input type="password" name="password2"/><br/>

<input type="submit">

</form>

</body>

</html>

JavaScript Number Validation:

Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

<!DOCTYPE html>

<html>

<head>

<script>
function validate(){

var num=document.myform.num.value;

if (isNaN(num)){

document.getElementById("numloc").innerHTML="Enter Numeric value only";

return false;

}else{

return true;

</script>

</head>

<body>

<form name="myform" action="http://www.javatpoint.com/javascriptpages/valid.jsp"


onsubmit="return validate()" >

Number: <input type="text" name="num"><span id="numloc"></span><br/>

<input type="submit" value="submit">

</form>

</body>

</html>

JavaScript validation with image: Let’s see an interactive JavaScript form validation example
that displays correct and incorrect image if input is correct or incorrect.

<html>

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

function validate(){

var name=document.f1.name.value;

var passwordlength=document.f1.password.value.length;

var status=false;

if(name==""){

document.getElementById("namelocation").innerHTML=

" <img src='http://www.javatpoint.com/javascriptpages/images/unchecked.gif'/> Please enter


your name";

status=false;

}else{

document.getElementById("namelocation").innerHTML=" <img
src='http://www.javatpoint.com/javascriptpages/images/checked.gif'/>";

status=true;

if(passwordlength<6){

document.getElementById("passwordlocation").innerHTML=

" <img src='http://www.javatpoint.com/javascriptpages/images/unchecked.gif'/> Password must


be greater than 6";

status=false;

}else{

document.getElementById("passwordlocation").innerHTML=" <img
src='http://www.javatpoint.com/javascriptpages/images/checked.gif'/>";

}
return status;

</script>

<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp"


onsubmit="return validate()">

<table>

<tr><td>Name:</td><td><input type="text" name="name"/>

<span id="namelocation" style="color:red"></span></td></tr>

<tr><td>Password:</td><td><input type="password" name="password"/>

<span id="passwordlocation" style="color:red"></span></td></tr>

<tr><td colspan="2"><input type="submit" value="register"/> </td></tr>

</table>

</form>

</body>

</html>

AJAX

AJAX = Asynchronous JavaScript And XML.AJAX is not a programming language.

AJAX just uses a combination of:

 A browser built-in XMLHttpRequest object (to request data from a web server)
 JavaScript and HTML DOM (to display or use the data).
 AJAX allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.

How AJAX Works:

Step1:The XMLHttpRequest Object:

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a web server behind the scenes.
This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object:

All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-
in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Step2:AJAX - Send a Request To a Server:

To send a request to a server, we use the open() and send() methods of


the XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true); //method,URL,asynchronous(true)
// When true, the request runs asynchronously, meaning JavaScript does not pause execution
while waiting for the response.
xhttp.send();

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

 A cached file is not an option (update a file or database on the server).


 Sending a large amount of data to the server (POST has no size limitations).
 Sending user input (which can contain unknown characters), POST is more robust and
secure than GET.

Method Description

open(method, url, async) Specifies the type of request

method: the type of request: GET or POST


url: the server (file) location
async: true (asynchronous) or false (synchronous)

send() Sends the request to the server (used for GET)

send(string) Sends the request to the server (used for POST)

Step3:AJAX - Server Response:


The onreadystatechange Property:

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.

syntax

xhttp.onreadystatechange = function() // This anonymous function is executed


every time the readyState property of the XMLHttpRequest object changes. The
readyState property represents the state of the XMLHttpRequest

if(this.readystate==4 && this.status==200)

document.getElementById("demo").innerHTML = this.responseText;

};

Why Use onreadystatechange?

 Allows handling of asynchronous responses.


 Ensures the response is processed only when fully loaded (readyState == 4).
 Prevents errors caused by attempting to access response data too early.

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")

The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

Server Response Properties:

Property Description

responseText get the response data as a string

responseXML get the response data as XML data

Example
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "12.txt",true);
xhttp.send();
}
</script>
</body>
</html>

AJAX Database: AJAX can be used for interactive communication with a database.

How a web page can fetch information from a database with AJAX:

<!DOCTYPE html>

<html>

<head>

<script>

function showUser(str) {
if (str=="") {

document.getElementById("txtHint").innerHTML="";

return;

var xmlhttp=new XMLHttpRequest();

xmlhttp.onreadystatechange=function() {

if (this.readyState==4 && this.status==200) {

document.getElementById("txtHint").innerHTML=this.responseText;

xmlhttp.open("GET","getuser.php?q="+str,true);

xmlhttp.send();

</script>

</head>

<body>

<form>

<select name="users" onchange="showUser(this.value)">

<option value="">Select a person:</option>

<option value="1">Peter Griffin</option>

<option value="2">Lois Griffin</option>

<option value="3">Joseph Swanson</option>

<option value="4">Glenn Quagmire</option>


</select>

</form>

<br>

<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>

</html>

Php file

<!DOCTYPE html>

<html>

<head>

<style>

table {

width: 100%;

border-collapse: collapse;

table, td, th {

border: 1px solid black;

padding: 5px;

}
th {text-align: left;}

</style>

</head>

<body>

<?php

$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','','test');

if (!$con) {

die('Could not connect: ' . mysqli_error($con));

mysqli_select_db($con,"user");

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysqli_query($con,$sql);

echo "<table>

<tr>

<th>Firstname</th>

<th>Lastname</th>

<th>Age</th>

<th>Hometown</th>
<th>Job</th>

</tr>";

while($row = mysqli_fetch_array($result)) {

echo "<tr>";

echo "<td>" . $row['Firstname'] . "</td>";

echo "<td>" . $row['Lastname'] . "</td>";

echo "<td>" . $row['Age'] . "</td>";

echo "<td>" . $row['Hometown'] . "</td>";

echo "<td>" . $row['Job'] . "</td>";

echo "</tr>";

echo "</table>";

mysqli_close($con);

?>

</body>

</html>

AJAX XML: AJAX can be used for interactive communication with an XML file.

<!DOCTYPE html>

<html>

<style>

table,th,td {

border : 1px solid black;

border-collapse: collapse;

}
th,td {

padding: 5px;

</style>

<body>

<h1>The XMLHttpRequest Object</h1>

<button type="button" onclick="loadDoc()">Get my CD collection</button>

<br><br>

<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>

</body>

</html>

jQuery

What is jQuery?

o jQuery is a small and lightweight JavaScript library.


o jQuery is cross-platform.
o jQuery means "write less do more".
o jQuery simplifies AJAX call and DOM manipulation.

o jQuery Features: HTML manipulation


o DOM manipulation
o DOM element selection
o CSS manipulation
o Effects and Animations
o Utilities
o AJAX
o HTML event methods

Why jQuery is required?

Sometimes, a question can arise that what is the need of jQuery or what difference it makes on
bringing jQuery instead of AJAX/ JavaScript? If jQuery is the replacement of AJAX and
JavaScript? For all these questions, you can state the following answers.

o It is very fast and extensible.


o It facilitates the users to write UI related function codes in minimum possible lines.
o It improves the performance of an application.
o Browser's compatible web applications can be developed.
o It uses mostly new features of new browsers.

So, you can say that out of the lot of JavaScript frameworks, jQuery is the most popular and the
most extendable. Many of the biggest companies on the web use jQuery.

Some of these companies are:

o Microsoft
o Google
o IBM
o Netflix

jQuery Get Started:

There are several ways to start using jQuery on your web site. You can:

 Download the jQuery library from jQuery.com


 Include jQuery from a CDN
A CDN (Content Delivery Network) is a network of distributed servers that deliver web
content (such as images, videos, scripts, and stylesheets) to users based on their
geographical location. CDNs help improve website performance by reducing load times
and increasing reliability.

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

Popular CDNs

Google CDN – https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js

Cloudflare CDN – Used for caching and security.

Bootstrap CDN – Loads Bootstrap styles & scripts.

jsDelivr CDN – Free and fast open-source CDN.

Downloading jQuery:

There are two versions of jQuery available for downloading:

 Production version - this is for your live website because it has been minified and
compressed
 Development version - this is for testing and development (uncompressed and readable
code)

Both versions can be downloaded from jQuery.com.

The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag
(notice that the <script> tag should be inside the <head> section):

<head>
<script src="jquery-3.5.1.min.js"></script>
</head>

jQuery Syntax:

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).

Basic syntax is: $(selector).action()

 A $ sign to define/access jQuery


 A (selector) to "query (or find)" HTML elements
 A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

The Document Ready Event


$(document).ready(function(){
// jQuery methods go here...
});

OR

$(function(){

// jQuery methods go here...

});

This is to prevent any jQuery code from running before the document is finished
loading (is ready).

It is good practice to wait for the document to be fully loaded and ready before
working with it. This also allows you to have your JavaScript code before the
body of your document, in the head section.

Here are some examples of actions that can fail if methods are run before the
document is fully loaded:
 Trying to hide an element that is not created yet
 Trying to get the size of an image that is not loaded yet

Example: <!DOCTYPE html>

<html>

<head>

<title>First jQuery Example</title>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.js">

</script>

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

$(document).ready(function() {

$("p").css("background-color", "cyan");

});

</script>

</head>

<body>

<p>The first paragraph is selected.</p>

<p>The second paragraph is selected.</p>

<p>The third paragraph is selected.</p>

</body>

</html>

jQuery Selectors

jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes,
types, attributes, values of attributes and much more. It's based on the existing CSS Selectors,
and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().

The element Selector:

The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

Example:

When a user clicks on a button, all <p> elements will be hidden:

<!DOCTYPE html>

<html>

<head>

<script src=" https://code.jquery.com/jquery-3.7.1.js "></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("p").hide();

});

});

</script>

</head>

<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>


<button>Click me to hide paragraphs</button>

</body>

</html>

The #id Selector:

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.

To find an element with a specific id, write a hash character, followed by the id of the HTML
element:

$("#test")

Example:

When a user clicks on a button, the element with id="test" will be hidden:

<!DOCTYPE html>

<html>

<head>

<script src=" https://code.jquery.com/jquery-3.7.1.js "></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("#test").hide();

});

});

</script>

</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>

<p id="test">This is another paragraph.</p>

<button>Click me</button>

</body>

</html>

The .class Selector:

The jQuery .class selector finds elements with a specific class.

To find elements with a specific class, write a period character, followed by the name of the
class:

$(".test")

Example

When a user clicks on a button, the elements with class="test" will be hidden:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script>
</head>
<body>

<h2 class="test">This is a heading</h2>


<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me</button>

</body>
</html>

Syntax Description

$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$(":button") Selects all <button> elements and <input> elements of


type="button"

$("tr:even") Selects all even <tr> elements

$("tr:odd") Selects all odd <tr> elements

Mouse Events

i) click():

The click() method attaches an event handler function to an HTML element.

The function is executed when the user clicks on the HTML element.

The following example says: When a click event fires on a <p> element; hide the
current <p> element:

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("p").click(function(){

$(this).hide();

});
});

</script>

</head>

<body>

<p>If you click on me, I will disappear.</p>

<p>Click me away!</p>

<p>Click me too!</p>

</body></html>

ii) dblclick():

The dblclick() method attaches an event handler function to an HTML element.

The function is executed when the user double-clicks on the HTML element:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("p").dblclick(function(){

$(this).hide();

});

});

</script>

</head>
<body>

<p>If you double-click on me, I will disappear.</p>

<p>Click me away!</p>

<p>Click me too!</p>

</body>

</html>

iii) mouseenter():

The mouseenter() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer enters the HTML element:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("#p1").mouseenter(function(){

alert("You entered p1!");

});

});

</script>

</head>
<body>

<p id="p1">Enter this paragraph.</p>

</body>

</html>

iv) mouseleave():

The mouseleave() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer leaves the HTML element:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("#p1").mouseleave(function(){

alert("Bye! You now leave p1!");

});

});

</script>

</head>

<body>

<p id="p1">This is a paragraph.</p>

</body>

</html>
v) mousedown():

The mousedown() method attaches an event handler function to an HTML element.

The function is executed, when the left, middle or right mouse button is pressed down, while the
mouse is over the HTML element:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("#p1").mousedown(function(){

alert("Mouse down over p1!");

});

});

</script>

</head>

<body>

<p id="p1">This is a paragraph.</p>

</body>

</html>

vi) mouseup():

The mouseup() method attaches an event handler function to an HTML element.

The function is executed, when the left, middle or right mouse button is released, while the
mouse is over the HTML element:
<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("#p1").mouseup(function(){

alert("Mouse up over p1!");

});

});

</script>

</head>

<body>

<p id="p1">This is a paragraph.</p>

</body>

</html>

Form Events

i) submit() : The submit event occurs when a form is submitted.

This event can only be used on <form> elements.

The submit() method triggers the submit event, or attaches a function to run when a submit event
occurs.

Syntax:

Trigger the submit event for the selected elements:


$(selector).submit()

Example: <!DOCTYPE html>


<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
$("button").click(function(){
$("form").submit();
});
});
</script>
</head>
<body>

<form action="">
First name: <input type="text" name="FirstName" value="Mickey"><br>
Last name: <input type="text" name="LastName" value="Mouse"><br>
</form>

<button>Trigger submit event</button>

</body>
</html>

ii) change():The change event occurs when the value of an element has been changed (only
works on <input>, <textarea> and <select> elements).

The change() method triggers the change event, or attaches a function to run when a change
event occurs.

Syntax:

Trigger the change event for the selected elements:

$(selector).change()

Attach a function to the change event:

$(selector).change(function)

Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input").change();
});
});
</script>
</head>
<body>

<p>Click the button to trigger the change event (even if the element has not been changed).</p>

<button>Trigger change event for input field</button>

<p>Enter your name: <input value="Donald" onchange="alert(this.value)" type="text"></p>

</body>
</html>

iii)focus():The focus event occurs when an element gets focus (when selected by a mouse click
or by "tab-navigating" to it).

The focus() method triggers the focus event, or attaches a function to run when a focus event
occurs.

Syntax:

Trigger the focus event for selected elements:

$(selector).focus()

Attach a function to the focus event:

$(selector).focus(function)

Example:

<!DOCTYPE html>

<html>

<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("#btn1").click(function(){

$("input").focus();

$("p").html("focus event triggered");

});

$("#btn2").click(function(){

$("input").blur();

$("p").html("blur event triggered");

});

});

</script>

</head>

<body>

Enter your name: <input type="text">

<br><br>

<button id="btn1">Trigger focus event</button>

<button id="btn2">Trigger blur event</button>

<p style="color:red"></p>

</body>

</html>

iv) blur():

The blur() method attaches an event handler function to an HTML form field.
The function is executed when the form field loses focus:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("input").focus(function(){

$(this).css("background-color", "yellow");

});

$("input").blur(function(){

$(this).css("background-color", "green");

});

});

</script>

</head>

<body>

Name: <input type="text" name="fullname"><br>

Email: <input type="text" name="email">

</body>

</html>
DOM Manipulation

jQuery provides various methods to add, edit or delete DOM element(s) in the HTML page.

The following table lists some important methods to add/remove new DOM elements.

Method Description
append() Inserts content at the end of the selected elements
before() Inserts content before the selected elements.
after() Inserts content after the selected elements.
prepend() Inserts content at the beginning of the selected elements
remove() Removes element(s) from DOM which is specified by selector.
replaceAll() Replace target element(s) with specified element.
wrap() Wrap an HTML structure around each element which is specified by selector.

The following figure shows how the DOM manipulation methods add new elements.

i) jQuery after() Method:

The jQuery after() method inserts content (new or existing DOM elements) after target
element(s) which is specified by a selector.

Syntax:
$('selector expression').after('content');

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<script>
$(document).ready(function () {

$('#div1').after('<div style="background-color:yellow"> New div </div>');

});
</script>
<style>
div{
border: 1px solid;
background-color:red;
margin: 2px 0 2px 0;
}
</style>
</head>
<body>
<h1>Demo: jQuery after() method </h1>

<div id="div1">division1
</div>

<div id="div2">division2
</div>
</body>
</html>

ii)jQuery before() Method:

The jQuery before() method inserts content (new or existing DOM elements) before target
element(s) which is specified by a selector.

Syntax:
$('selector expression').before('content');

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js">

</script>

<script>

$(document).ready(function () {

$('#div1').before('<div style="background-color:yellow"> New div </div>');

});

</script>
<style>

div{

border: 1px solid;

background-color:red;

margin: 2px 0 2px 0;

</style>

</head>

<body>

<h1>Demo: jQuery before() method </h1>

<div id="div1">div 1

</div>

<div id="div2">div 2

</div>

</body>

</html>

iii)jQuery append() Method:

The jQuery append() method inserts content to the end of target element(s) which is specified
by a selector.

Syntax:
$('selector expression').append('content');

<!DOCTYPE html>

<html>
<head>

<script src="https://code.jquery.com/jquery-3.7.1.js">

</script>

<script>

$(document).ready(function () {

$('p').append('World!');

});

</script>

</head>

<body>

<h1>Demo: jQuery append() method </h1>

<p>Hello </p>

</body>

</html>

iv) jQuery prepend() Method:

The jQuery prepend() method inserts content at the beginning of an element(s) specified by a
selector.

Syntax:

$('selector expression').prepend('content');

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>

<script>

$(document).ready(function ()

$('div').prepend('<p>This is prepended paragraph</p>');

});

</script>

</head>

<body>

<h1>Demo: jQuery prepend() method </h1>

<div>

<label>This is div.</label>

</div>

</body>

</html>

prepend() Inside the element, at the beginning

before() Outside the element, before it

v) jQuery remove() Method:

The jQuery remove() method removes element(s) as specified by a selector.

Syntax:
$('selector expression').remove();

<!DOCTYPE html>
<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js">

</script>

<script>

$(document).ready(function () {

$('label').remove();

});

</script>

</head>

<body>

<h1>Demo: jQuery remove() method </h1>

<div>This is div.

<label>This is label.</label>

</div>

</body></html>

jQuery empty() Method


The jQuery empty() method removes the child elements of the selected
element(s)

<!DOCTYPE html>

<html>

<head>
<script src=" https://code.jquery.com/jquery-3.7.1.js "></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("#div1").empty();

});

});

</script>

</head>

<body>

<div id="div1" style="height:100px;width:300px;border:1px solid black;background-


color:yellow;">

This is some text in the div.

<p>This is a paragraph in the div.</p>

<p>This is another paragraph in the div.</p>

</div>

<br>

<button>Empty the div element</button>

</body>
</html>

vi) jQuery replaceAll() Method

The jQuery replaceAll() method replaces all target elements with specified element(s).

Syntax:
$('content string').replaceAll('selector expression');

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js">

</script>

<script>

$(document).ready(function () {

$('<span>This is span</span>').replaceAll('p');

});

</script>

</head>

<body>

<h1>Demo: jQuery replaceAll() method </h1>

<div>

<p>This is paragraph.</p>

</div>

<p>This is another paragraph.</p>

</body>
</html>

vii)jQuery wrap() Method:

The jQuery wrap() method wrap each target element with specified content element.

Syntax:
$('selector expression').wrap('content string');
Example:
<!DOCTYPE html>

<html>
<head>
<script src=" https://code.jquery.com/jquery-3.7.1.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").wrap("<div></div>");
});
});
</script>
<style>
div{background-color: yellow;}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Wrap a div element around each p element</button>

</body>
</html>

Get Content - text(), html(), and val()


Three simple, but useful, jQuery methods for DOM manipulation are:

 text() - Sets or returns the text content of selected elements


 html() - Sets or returns the content of selected elements (including HTML
markup)
 val() - Sets or returns the value of form fields

<!DOCTYPE html>

<html>

<head>

<script src=" https://code.jquery.com/jquery-3.7.1.js "></script>

<script>

$(document).ready(function(){

$("#btn1").click(function(){

alert("Text: " + $("#test").text());

});

$("#btn2").click(function(){

alert("HTML: " + $("#test").html());

});

});

</script>

</head>

<body>
<p id="test">This is some <b>bold</b> text in a paragraph.</p>

<button id="btn1">Show Text</button>

<button id="btn2">Show HTML</button>

</body>

</html>

jQuery val() method

The following example demonstrates how to get the value of an input field with
the jQuery val() method:

<!DOCTYPE html>

<html>

<head>

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

<script>

$(document).ready(function(){

$("button").click(function(){

alert("Value: " + $("#test").val());

});

});

</script>

</head>

<body>
<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>

<button>Show Value</button>

</body>

</html>

Get Attributes - attr()


The jQuery attr() method is used to get attribute values.

The following example demonstrates how to get the value of the href attribute
in a link:

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></
script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("#abc").attr("href"));
});
});
</script>
</head>
<body>

<p><a href="https://www.youtube.com" id="abc">youtube.com</a></p>


<button>Show href Value</button>

</body>
</html>

Effects And Animation

i) jQuery hide() and show():With jQuery, you can hide and show HTML elements with
the hide() and show() methods.
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
ii) 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()

a) jQuery fadeIn() Method:

 The jQuery fadeIn() method is used to fade in a hidden element.


 Syntax:
 $(selector).fadeIn(speed,callback);
 The optional speed parameter specifies the duration of the effect. It can take the
following values: "slow", "fast", or milliseconds.
 The optional callback parameter is a function to be executed after the fading completes.

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("#div1").fadeIn();

$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);

});

});

</script>

</head>

<body>

<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:red;"></div><br>

<div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></


div><br>

<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>

</body>

</html>

b) jQuery fadeOut() Method:

The jQuery fadeOut() method is used to fade out a visible element.

Syntax:

$(selector).fadeOut(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading completes.

Example:

<!DOCTYPE html>
<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("#div1").fadeOut();

$("#div2").fadeOut("slow");

$("#div3").fadeOut(3000);

});

});

</script>

</head>

<body>

<p>Demonstrate fadeOut() with different parameters.</p>

<button>Click to fade out boxes</button><br><br>

<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>

<div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>

<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

</body>

</html>

c) jQuery fadeToggle() Method:

The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.
If the elements are faded out, fadeToggle() will fade them in.

If the elements are faded in, fadeToggle() will fade them out.

Syntax:

$(selector).fadeToggle(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading completes.

Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
});
</script>
</head>
<body>
<p>Demonstrate fadeToggle() with different speed parameters.</p>
<button>Click to fade in/out boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>
<br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div>
<br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>
</body>
</html>
d) jQuery fadeTo() Method:

The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).

Syntax:

$(selector).fadeTo(speed,opacity,callback);

The required speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.

The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value
between 0 and 1).

The optional callback parameter is a function to be executed after the function completes.

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("#div1").fadeTo("slow", 0.15);

$("#div2").fadeTo("slow", 0.4);

$("#div3").fadeTo("slow", 0.7);

});

});
</script>

</head>

<body>

<p>Demonstrate fadeTo() with different parameters.</p>

<button>Click to fade boxes</button><br><br>

<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>

<div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>

<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

</body>

</html>

iii) jQuery Sliding Methods:

With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

 slideDown()
 slideUp()
 slideToggle()

a) jQuery slideDown() Method:

 The jQuery slideDown() method is used to slide down an element.


 Syntax:
 $(selector).slideDown(speed,callback);
 The optional speed parameter specifies the duration of the effect. It can take the
following values: "slow", "fast", or milliseconds.
 The optional callback parameter is a function to be executed after the sliding completes.

Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
</body>
</html>
b) jQuery slideUp() Method:

The jQuery slideUp() method is used to slide up an element.

Syntax:
$(selector).slideUp(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the sliding completes.

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(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;

</style>

</head>

<body>

<div id="flip">Click to slide up panel</div>

<div id="panel">Hello world!</div>

</body>

</html>

c) jQuery slideToggle() Method:

The jQuery slideToggle() method toggles between the slideDown() and slideUp() methods.

If the elements have been slid down, slideToggle() will slide them up.

If the elements have been slid up, slideToggle() will slide them down.

$(selector).slideToggle(speed,callback);

The optional speed parameter can take the following values: "slow", "fast", milliseconds.

The optional callback parameter is a function to be executed after the sliding completes.

iv) jQuery Animations - The animate() Method:

The jQuery animate() method is used to create custom animations.

Syntax:

$(selector).animate({params},speed,callback);

The required params parameter defines the CSS properties to be animated.


The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the animation completes.

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("div").animate({left: '250px'});

});

});

</script>

</head>

<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate
the position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>

</html>
a) jQuery animate() - Manipulate Multiple Properties: multiple properties can be
animated at the same time.
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate
the position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
b) jQuery animate() - Using Relative Values:

It is also possible to define relative values (the value is then relative to the element's current
value). This is done by putting += or -= in front of the value:

Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=150px',
width: '+=150px'
});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate
the position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
c) jQuery animate() - Using Pre-defined Values:

You can even specify a property's animation value as "show", "hide", or "toggle":

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
height: 'toggle'
});
});
});
</script>
</head>
<body>
<p>Click the button multiple times to toggle the animation.</p>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate
the position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
d) jQuery animate() - Uses Queue Functionality:

By default, jQuery comes with queue functionality for animations.

This means that if you write multiple animate() calls after each other, jQuery creates an
"internal" queue with these method calls. Then it runs the animate calls ONE by ONE.

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.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>

</head>

<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate
the position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>

</html>

iv) jQuery Stop Animations:

The jQuery stop() method is used to stop an animation or effect before it is finished.

The stop() method works for all jQuery effect functions, including sliding, fading and custom
animations.

Syntax:

$(selector).stop(stopAll,goToEnd);
The optional 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.

The optional goToEnd parameter specifies whether or not to complete the current animation
immediately. Default is false.

So, by default, the stop() method kills the current animation being performed on the selected
element.

Example:

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.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>

</head>

<body>

<button id="stop">Stop sliding</button>

<div id="flip">Click to slide down panel</div>

<div id="panel">Hello world!</div>

</body>

</html>

jQuery Traversing – Filtering

Traversing
Traversing in jQuery allows you to navigate through the DOM (Document Object Model) to find,
filter, or manipulate elements relative to a selected element.
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

 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>

*An ancestor is a parent, grandparent, great-grandparent, and so on.

*A descendant is a child, grandchild, great-grandchild, and so on.


Siblings share the same parent.

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.

The next chapters will show us how to travel up, down and sideways in the DOM tree.

Traversing Up the DOM Tree

Three useful jQuery methods for traversing up the DOM tree are:
 parent()

 parents()

 parentsUntil()

jQuery parent() Method

 The parent() method returns the direct parent element of the selected element.
 This method only traverse a single level up the DOM tree.

<!DOCTYPE html>

<html>

<head>

<style>

.ancestors * {

display: block;

border: 2px solid lightgrey;

color: lightgrey;

padding: 5px;

margin: 15px;

</style>

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

<script>
$(document).ready(function(){

$("span").parent().css({"color": "red", "border": "2px solid red"});

});

</script>

</head>

<body>

<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>

</body>

</html>

jQuery parents() Method


The parents() method returns all ancestor elements of the selected element, all the way up to the
document's root element (<html>).

<!DOCTYPE html>

<html>

<head>

<style>

.ancestors * {

display: block;

border: 2px solid lightgrey;

color: lightgrey;

padding: 5px;

margin: 15px;

</style>

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

<script>

$(document).ready(function(){

$("span").parents().css({"color": "red", "border": "2px solid red"});

});

</script>

</head>
<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>

<!-- The outer red border, before the body element, is the html element (also an ancestor) -->

</html>

parentsUntil() Method
The parentsUntil() method returns all ancestor elements between two given arguments.

The following example returns all ancestor elements between a <span> and a <div> element

<!DOCTYPE html>

<html>

<head>

<style>

.ancestors * {

display: block;

border: 2px solid lightgrey;

color: lightgrey;

padding: 5px;

margin: 15px;
}

</style>

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

<script>

$(document).ready(function(){

$("span").parentsUntil("div").css({"color": "red", "border": "2px solid red"});

});

</script>

</head>

<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>

</html>

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.

Traversing Down the DOM Tree


Two useful jQuery methods for traversing down the DOM tree are:

 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.
 The following example returns all elements that are direct children of each <div> elements:

<!DOCTYPE html>

<html>

<head>

<style>

.descendants * {

display: block;

border: 2px solid lightgrey;

color: lightgrey;

padding: 5px;

margin: 15px;

</style>

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

<script>

$(document).ready(function(){

$("div").children().css({"color": "red", "border": "2px solid red"});

});

</script>

</head>

<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>

</html>

jQuery find() Method

The find() method returns descendant elements of the selected element, all the way down to the last
descendant.

The following example returns all <span> elements that are descendants of <div>:

<!DOCTYPE html>

<html>

<head>

<style>

.descendants * {

display: block;

border: 2px solid lightgrey;

color: lightgrey;

padding: 5px;

margin: 15px;

}
</style>

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

<script>

$(document).ready(function(){

$("div").find("span").css({"color": "red", "border": "2px solid red"});

});

</script>

</head>

<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>

</html>

jQuery Traversing - Siblings

With jQuery you can traverse sideways in the DOM tree to find siblings of an element.

Siblings share the same parent.

raversing Sideways in The DOM Tree

There are many useful jQuery methods for traversing sideways in the DOM tree:
 siblings()

 next()

 nextAll()

 nextUntil()

 prev()

 prevAll()

 prevUntil()

JQuery siblings() Method

 The siblings() method returns all sibling elements of the selected element.
 The following example returns all sibling elements of <h2>:

<!DOCTYPE html>

<html>

<head>

<style>

.siblings * {

display: block;

border: 2px solid lightgrey;

color: lightgrey;

padding: 5px;

margin: 15px;

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/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>

</html>

Filtering
Filtering in jQuery allows you to select specific elements from a set of matched elements. It helps refine
selections based on conditions like position, attributes, or relationships.

Method Description
.filter(selector) Selects elements that match the selector.
.not(selector) Excludes elements that match the selector.
.first() Selects the first element.
.last() Selects the last element.
.eq(index) Selects the element at the given index.
.has(selector) Selects elements that contain the specified selector.
.is(selector) Checks if at least one element matches the selector.

i) jQuery first() Method:

The first() method returns the first element of the specified elements.

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("div").first().css("background-color", "yellow");

});

</script>

</head>

<body

<h1>Welcome to My Homepage</h1>

<p>This is a paragraph.</p>

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

<p>A paragraph in a div.</p>

<p>Another paragraph in a div.</p>

</div>

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

<p>A paragraph in another div.</p>

<p>Another paragraph in another div.</p>

</div>

<br>

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

<p>A paragraph in another div.</p>

<p>Another paragraph in another div.</p>

</div>

</body>

</html>

ii) jQuery last() Method:

The last() method returns the last element of the specified elements.

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("div").last().css("background-color", "yellow");

});

</script>

</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>This is a paragraph.</p>

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

<p>A paragraph in a div.</p>

<p>Another paragraph in a div.</p>

</div>

<br>

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

<p>A paragraph in another div.</p>

<p>Another paragraph in another div.</p>

</div>

<br>

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

<p>A paragraph in another div.</p>

<p>Another paragraph in another div.</p>

</div>

</body>

</html>

iii)jQuery eq() method:

The eq() method returns an element with a specific index number of the selected elements.

The index numbers start at 0, so the first element will have the index number 0 and not 1.
<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("p").eq(1).css("background-color", "yellow");

});

</script>

</head>

<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald (index 0).</p>

<p>Donald Duck (index 1).</p>

<p>I live in Duckburg (index 2).</p>

<p>My best friend is Mickey (index 3).</p>

</body>

</html>

iv) jQuery filter() Method:

The filter() method lets you specify a criteria. Elements that do not match the criteria are
removed from the selection, and those that match will be returned.

<!DOCTYPE html>

<html>

<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

$(document).ready(function(){

$("p").filter(".intro").css("background-color", "yellow");

});

</script>

</head>

<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald.</p>

<p class="intro">I live in Duckburg.</p>

<p class="intro">I love Duckburg.</p>

<p>My best friend is Mickey.</p>

</body>

</html>

v)jQuery not() Method:

The not() method returns all elements that do not match the criteria.

Tip: The not() method is the opposite of filter().

<!DOCTYPE html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>
$(document).ready(function(){

$("p").not(".intro").css("background-color", "yellow");

});

</script>

</head>

<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald.</p>

<p class="intro">I live in Duckburg.</p>

<p class="intro">I love Duckburg.</p>

<p>My best friend is Mickey.</p>

</body>

</html>


Relative Position: Setting the top, right, bottom, and left properties
of an element with position: relative; property will cause it to adjust
from its normal position. The other objects or elements will not fill the
gap.
Syntax:
position: relative;
Absolute Position: An element with position: absolute; will cause it to
adjust its position with respect to its parent. If no parent is present,
then it uses the document body as parent.
position: absolute;
Fixed Position: Position: fixed; property applied to an element will
cause it to always stay in the same place even if the page is scrolled.
To position the element we use top, right, bottom, left properties.
Why Use Callback Functions?

o In JavaScript statements are executed line by line, but with effects, the next line of code
can run even before the effect is fully finished. This can lead to errors.
o To prevent such issues, you can create a callback function. It ensures that your code
runs only after the effect is complete.
o Remember to use them when dealing with asynchronous operations or effects to
maintain code correctness and avoid unexpected behavior.

You might also like