0% found this document useful (0 votes)
16 views38 pages

Unit 2 (WD)

AJAX (Asynchronous JavaScript and XML) is a set of web development techniques that enables web pages to communicate with a server in the background without refreshing the entire page, enhancing user experience and reducing server load. It utilizes technologies such as HTML, CSS, JavaScript, and server-side languages to perform asynchronous requests and update parts of a webpage dynamically. The document also discusses the differences between data formats like XML and JSON, and provides examples of using AJAX with both formats in web applications.

Uploaded by

versajatt2
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)
16 views38 pages

Unit 2 (WD)

AJAX (Asynchronous JavaScript and XML) is a set of web development techniques that enables web pages to communicate with a server in the background without refreshing the entire page, enhancing user experience and reducing server load. It utilizes technologies such as HTML, CSS, JavaScript, and server-side languages to perform asynchronous requests and update parts of a webpage dynamically. The document also discusses the differences between data formats like XML and JSON, and provides examples of using AJAX with both formats in web applications.

Uploaded by

versajatt2
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/ 38

UNIT-2(Web Development)

BCA 1st Year

What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.

It is not a programming language.


It is a set of web development techniques that allows web pages to communicate with a
server in the background without refreshing the entire page.

✅ Key Features of AJAX:

 Asynchronous: AJAX can send and receive data in the background (asynchronously).
 Partial Page Updates: Only a portion of the page is updated—no need to reload the full
webpage.
 Fast and Smooth UX: AJAX makes web applications faster and more responsive.
 Data Formats: Although "XML" is in the name, AJAX works with many formats like
JSON, HTML, Text, or XML.

📦 Technologies Involved in AJAX


AJAX uses a combination of the following:

Technology Role
HTML/XHTML For the structure of the page
CSS For styling the page
JavaScript To interact with the page and make AJAX requests
DOM For updating parts of the page dynamically
The object used in JavaScript to send/receive
XMLHttpRequest
requests
Server-Side Language (PHP, ASP.NET,
To process and return the data
etc.)
🔁 How AJAX Works (Step-by-Step Flow)
1. A user event (like clicking a button) occurs on the web page.
2. JavaScript creates an XMLHttpRequest object.
3. The request is sent to the web server (e.g., via PHP).
4. The server processes the request and sends back a response.
5. JavaScript receives the response and updates the webpage without reloading.

🧪 Basic AJAX Example


HTML:
<button onclick="loadData()">Click Me</button>
<div id="result"></div>

Why Do We Need AJAX?


✅ 1. Improve User Experience (UX)

AJAX allows parts of a web page to update without reloading the entire page, which means:

 Faster interactions
 No flickering or full page reloads
 Feels like a smooth, responsive app

🔁 Example: When you "like" a post on Instagram or Facebook, the like button updates instantly
without reloading the page—that's AJAX!

✅ 2. Reduce Server Load and Bandwidth

AJAX fetches only the required data, not the whole page.

 Less data transferred = faster response


 Helps server handle more requests efficiently

📉 Example: Instead of reloading the full 2MB page, it might just request a 10KB JSON file.
✅ 3. Asynchronous Communication

AJAX works in the background.

 You can keep interacting with the page while data is being fetched or submitted.
 This avoids freezing or blocking the interface.

⚙️Example: While submitting a form, the user can continue browsing without interruption.

✅ 4. Dynamic Content Loading

AJAX enables loading new data or components based on user action without a page refresh.

Example: Infinite scroll in Facebook, YouTube, or Instagram loads more posts automatically as
you scroll.

✅ 5. Form Validation and Submission

AJAX can:

 Validate form fields instantly (e.g., checking username availability)


 Submit forms and show a response without redirecting

📝 Example: Signup forms that check if your email is already registered.

✅ 6. Better Performance for Web Apps

AJAX is essential in building Single Page Applications (SPAs) like Gmail, Google Maps, or
Trello, where:

 Pages never fully reload


 Only dynamic content is updated as needed

How AJAX Works


AJAX allows web applications to send and receive data from a server asynchronously without
refreshing the web page.

Here’s a step-by-step explanation of how it works behind the scenes:


🔁 Step-by-Step Working of AJAX

1. User Event Happens


A user performs an action on a webpage (like clicking a button or typing in a search box).
2. JavaScript Creates an XMLHttpRequest Object
JavaScript creates an instance of the XMLHttpRequest object (or uses fetch in modern
code) to handle the request.
3. Request is Configured
The request is set up with the type (GET or POST) and the URL of the server-side script
(e.g., data.php).
4. Request is Sent to the Server
The request is sent asynchronously, meaning the user can still interact with the page
while waiting for a response.
5. Server Processes the Request
The server (e.g., with PHP, Python, Node.js, etc.) receives the request, processes it (e.g.,
fetches data from a database), and sends a response back.
6. JavaScript Receives the Response
JavaScript receives the server's response (in text, JSON, XML, etc.) via the
onreadystatechange event (or .then() with fetch).
7. Web Page is Updated Dynamically
JavaScript updates part of the page content using DOM manipulation (e.g., innerHTML),
without refreshing the whole page.
8. 1. Client-Side: Handling AJAX Requests (JavaScript)
9. There are two main ways to send an AJAX request in JavaScript:
10.✅ A. Using XMLHttpRequest
11. <button onclick="sendAjax()">Click Me</button>
12. <div id="response"></div>
13.
14. <script>
15. function sendAjax() {
16. var xhr = new XMLHttpRequest(); // Create XMLHttpRequest object
17. xhr.open("GET", "server.php", true); // Set request method and URL
18.
19. xhr.onreadystatechange = function () {
20. if (xhr.readyState === 4 && xhr.status === 200) {
21. // Handle the response
22. document.getElementById("response").innerHTML =
xhr.responseText;
23. }
24. };
25.
26. xhr.send(); // Send the request
27. }
28. </script>
29.

30.✅ B. Using fetch() (Modern Method)


31. javascript
32. CopyEdit
33. function sendAjax() {
34. fetch("server.php")
35. .then(response => response.text())
36. .then(data => {
37. document.getElementById("response").innerHTML = data;
38. })
39. .catch(error => console.error("Error:", error));
40. }
41.

42. 📦 2. Server-Side: Handling AJAX Requests (PHP


Example)
43. server.php
44. <?php
45. // This is where the server responds to the AJAX request
46. echo "Hello from the server!";
47. ?>
48. 🔁 This file can also return JSON or handle POST data, like:
49. <?php
50. $name = $_POST['name'];
51. echo "Hello, " . $name;
52. ?>

1. XML (eXtensible Markup Language)


✅ What is XML?

 XML is a markup language that stores data in a tree structure.


 It is self-descriptive, meaning the tags describe the data.
 Used traditionally for data exchange before JSON became popular.

🧾 Example:
<student>
<name>John</name>
<age>22</age>
<course>Computer Science</course>
</student>

In AJAX:

You can receive an XML response and parse it using JavaScript.

var xhr = new XMLHttpRequest();


xhr.open("GET", "data.xml", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var xml = xhr.responseXML;
var name = xml.getElementsByTagName("name")
[0].childNodes[0].nodeValue;
console.log("Name:", name);
}
};
xhr.send();

🧬 2. JSON (JavaScript Object Notation)


✅ What is JSON?

 JSON is a lightweight data-interchange format.


 It's easy to read and write for humans and easy to parse by machines.
 Now the preferred format for AJAX due to simplicity and compatibility with
JavaScript.

🧾 Example:
{
"name": "John",
"age": 22,
"course": "Computer Science"
}

In AJAX:

You can receive a JSON response and convert it using JSON.parse() or automatically with
fetch().

fetch("data.json")
.then(response => response.json())
.then(data => {
console.log("Name:", data.name);
console.log("Age:", data.age);
});

🆚 Comparison Table: XML vs JSON


Feature XML JSON
Format Tag-based Key-value pair (object-like)
Readability More verbose Cleaner and simpler
Size Larger (more tags) Smaller (lightweight)
Parsing More complex (DOM parser) Easy with JSON.parse()
Feature XML JSON
Speed Slower Faster

What is JSON?
JSON (JavaScript Object Notation) is a format for storing and transporting data. It's often used when
data is sent from a server to a web page, or between APIs and applications.

✅ JSON Structure
{
"name": "John",
"age": 30,
"isStudent": false,
"hobbies": ["reading", "sports"],
"address": {
"city": "New York",
"zip": "10001"
}
}

 Keys are strings


 Values can be strings, numbers, arrays, booleans, or other objects

🔸 Working with JSON in Different Languages

🟦 JavaScript (Native to JSON)

✅ Parse JSON string to object


let jsonString = '{"name":"Alice","age":25}';
let obj = JSON.parse(jsonString);
console.log(obj.name); // Output: Alice

✅ Convert object to JSON string


let user = { name: "Bob", age: 28 };
let jsonStr = JSON.stringify(user);
console.log(jsonStr); // {"name":"Bob","age":28}

✅ Access nested values


let data = {
user: {
name: "Tom",
contact: {
email: "tom@example.com"
}
}
};
console.log(data.user.contact.email);

PHP (with json_encode() and json_decode())

✅ Convert PHP array to JSON


$data = ["name" => "Sam", "age" => 35];
$json = json_encode($data);
echo $json; // {"name":"Sam","age":35}

✅ Convert JSON to PHP array/object


$jsonStr = '{"name":"Sam","age":35}';
$array = json_decode($jsonStr, true); // as associative array
$object = json_decode($jsonStr); // as object

✅ Access values
echo $array['name']; // Sam
echo $object->name; // Sam

🔸 Common Operations
Task JavaScript Python PHP

Parse JSON
JSON.parse() json.loads() json_decode()
string

Stringify object JSON.stringify() json.dumps() json_encode()

fetch() or fs.readFile file_get_contents() +


Load from file json.load()
(Node) json_decode()

file_put_contents() +
Write to file fs.writeFile (Node) json.dump()
json_encode()

Loading HTML with AJAX


Imagine you want to load an HTML fragment (e.g., about.html) into a <div> when a user
clicks a button.
✅ Example Using jQuery (Most Common & Simple)
✅ HTML
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<button id="loadBtn">Load About Section</button>


<div id="content"></div>

<script>
$('#loadBtn').click(function() {
$('#content').load('about.html'); // Load HTML into div
});
</script>

</body>
</html>

✅ about.html
<h2>About Us</h2>
<p>We are passionate developers!</p>

🟡 When the user clicks the button, about.html is fetched and injected into the <div
id="content">.

Loading XML with AJAX


Loading XML with AJAX is a classic use case — it was actually the original purpose of AJAX
(Asynchronous JavaScript and XML). While JSON is more common nowadays, XML is still used in some
APIs and legacy systems.

Scenario
You have an XML file like this:

✅ books.xml
xml
CopyEdit
<books>
<book>
<title>JavaScript: The Good Parts</title>
<author>Douglas Crockford</author>
</book>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
</book>
</books>

You want to load this XML and display the book titles and authors on your web page.

✅ Using Vanilla JavaScript (XMLHttpRequest)


<!DOCTYPE html>
<html>
<head>
<title>Load XML with AJAX</title>
</head>
<body>

<button onclick="loadXML()">Load Books</button>


<div id="bookList"></div>

<script>
function loadXML() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "books.xml", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const xml = xhr.responseXML;
const books = xml.getElementsByTagName("book");
let output = "<h2>Book List</h2><ul>";

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


const title = books[i].getElementsByTagName("title")[0].textContent;
const author = books[i].getElementsByTagName("author")
[0].textContent;
output += `<li><strong>${title}</strong> by ${author}</li>`;
}

output += "</ul>";
document.getElementById("bookList").innerHTML = output;
}
};
xhr.send();
}
</script>
</body>
</html>
Loading JSON with AJAX

Using fetch() (Modern JavaScript)


html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>Load JSON with Fetch</title>
</head>
<body>

<button onclick="loadJSON()">Load Users</button>


<ul id="userList"></ul>

<script>
function loadJSON() {
fetch("data.json")
.then(response => response.json())
.then(data => {
let output = "";
data.forEach(user => {
output += `<li>${user.name} - Age: ${user.age}</li>`;
});
document.getElementById("userList").innerHTML = output;
})
.catch(error => console.error("Error loading JSON:", error));
}
</script>

</body>
</html>

What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library.

It makes things like:

 DOM manipulation,
 event handling,
 AJAX calls,
 and animations

much simpler using a cleaner, shorter syntax than plain JavaScript.


✅ Why Use jQuery?
🔹 Write less, do more
🔹 Simplifies complex JavaScript
🔹 Works across all browsers (cross-browser compatibility)
🔹 Easy DOM manipulation and traversal
🔹 Simple AJAX requests
🔹 Built-in animations and effects
🔹 Great for rapid development

✅ Basic jQuery Example


<!DOCTYPE html>
<html>
<head>
<title>Basic jQuery Example</title>
<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<h2>Welcome to jQuery!</h2>
<p id="message">Click the button below:</p>

<button id="myButton">Click Me</button>

<script>
// jQuery code
$(document).ready(function() {
$("#myButton").click(function() {
$("#message").text("Hello! You clicked the button.");
});
});
</script>

</body>
</html>

🔍 Explanation
 $(document).ready(): Makes sure the code runs after the page has fully loaded.
 $("#myButton").click(): Adds a click event listener to the button.
 $("#message").text(): Changes the text of the paragraph with ID message.
✅ What Happens?
When the page loads:

1. You see a heading, a paragraph, and a button.


2. When you click the button, the paragraph text changes.
3.

NEED OF JQUERY

Why jQuery Was Created


JavaScript was powerful, but:

 It had complex syntax


 Cross-browser issues were common (especially with Internet Explorer 😬)
 DOM manipulation was verbose
 AJAX was hard to implement consistently

So jQuery was built to simplify JavaScript for developers.

✅ Main Needs jQuery Solves


1. Simplified Syntax

You can do with one line in jQuery what might take several lines in plain JS.

👉 Example:

// Vanilla JS
document.getElementById("title").style.color = "blue";

// jQuery
$("#title").css("color", "blue");

2. Cross-Browser Compatibility

jQuery handles browser differences behind the scenes, so your code works the same in:

 Chrome
 Firefox
 Safari
 Edge
 (and even old versions of IE)

3. Easy DOM Manipulation

Add, remove, modify elements easily:

$("#box").hide(); // Hide element


$("#box").text("Hi"); // Change text
$("#box").addClass("active"); // Add a CSS class

4. Powerful Selectors (like CSS)

jQuery uses CSS-like selectors to target elements:

$("p:first") // First paragraph


$(".menu-item") // Elements with class
$("#header") // Element with ID
$("ul li a") // Nested anchor tags

5. Simplified AJAX

AJAX in vanilla JS is complicated. jQuery makes it super simple:

$.get("data.json", function(data) {
console.log(data);
});

6. Animation & Effects Built-In

No need for CSS transitions or libraries:

$("#box").fadeIn();
$("#box").slideUp();

7. Event Handling Made Easy

Attach events like .click(), .hover(), .keyup() etc. with ease:

$("#btn").click(function() {
alert("Clicked!");
});
8. Chainability

Do multiple things in one line:

$("#box").css("color", "red").slideUp().fadeIn();

Finding Elements in jQuery


You can use selectors to find elements just like in CSS — it’s powerful, flexible, and simple.

✅ Basic Selectors

Selector What It Selects Example


$("#id") Element with specific ID $("#header")
$(".class") All elements with that class $(".menu-item")
$("tag") All elements of that tag $("p")
$("div p") All <p> inside <div>
$("ul > li") Direct <li> children of <ul>
$("*") All elements

✅ Example:
<h1 id="mainHeading">Hello</h1>
<p class="info">Welcome!</p>
<p class="info">Enjoy your stay.</p>
$("#mainHeading").text("Hi there!"); // By ID
$(".info").css("color", "blue"); // By class
$("p").hide(); // All <p> tags

✅ Advanced Selectors

Selector Meaning
:first First matched element
:last Last matched element
:even, :odd Even/odd indexed elements
:eq(n) Specific index (starts at 0)
[attr=value] Attribute with specific value
input:checked Checked checkbox/radio
jQuery Selection Overview
In jQuery, selecting elements is extremely easy, and it's one of the reasons jQuery became so
popular. You can select elements using CSS-style selectors.

Basic Syntax for jQuery Selection:


$(selector).action()

Where:

 $ is the jQuery function,


 selector is a string that defines the elements you want to select,
 action() is a function you want to perform on the selected elements.

✅ Basic jQuery Selectors


1. ID Selector (#)

 Selects an element by its ID.

$("#myDiv").css("color", "blue");

2. Class Selector (.)

 Selects all elements with a specific class.

$(".menu").show();

3. Tag Selector

 Selects all elements of a specific HTML tag.

$("p").text("Updated Paragraph"); // Changes text of all <p> tags

✅ Advanced jQuery Selectors


4. Descendant Selector
 Selects an element inside another element.

$("#container p").css("font-size", "16px"); // All <p> inside #container

5. Child Selector (>)

 Selects direct children of an element.

$("ul > li").css("color", "green"); // Direct <li> elements inside <ul>

6. Attribute Selector ([attr=value])

 Selects elements based on an attribute.

$("input[type='text']").val("Hello World!"); // All <input> fields with


type="text"

7. Universal Selector (*)

 Selects all elements on the page.

$("*").css("border", "1px solid red"); // Adds a red border to all elements

✅ jQuery Pseudo-Selectors (Filters)


8. :first

 Selects the first element in a collection.

$("li:first").css("font-weight", "bold"); // First <li>

9. :last

 Selects the last element in a collection.

$("li:last").css("background", "yellow"); // Last <li>

10. :eq(n)

 Selects an element at a specific index (starting from 0).

$("li:eq(2)").css("color", "red"); // 3rd <li> element

11. :odd and :even


 Selects elements with odd or even indexes.

$("li:odd").css("background-color", "#f0f0f0"); // Odd <li>


$("li:even").css("background-color", "#d0d0d0"); // Even <li>

Getting Element Content in jQuery


jQuery provides various methods to retrieve the content inside an element, depending on whether
you're working with text content, HTML content, or attributes.

✅ 1. Getting Text Content (.text())


The .text() method retrieves the text content of an element. It doesn't include any HTML tags
or other elements inside the element.

Example:
<p id="para">This is a <b>paragraph</b> with <i>text</i>.</p>
javascript
CopyEdit
var text = $("#para").text();
console.log(text); // Output: "This is a paragraph with text."

Here, .text() returns the plain text, without the <b> and <i> tags.

✅ 2. Getting HTML Content (.html())


The .html() method retrieves the HTML content inside an element, including any nested
HTML tags.

Example:
<div id="content">
<p>This is a <b>bold</b> word.</p>
</div>
var htmlContent = $("#content").html();
console.log(htmlContent); // Output: "<p>This is a <b>bold</b> word.</p>"

Here, .html() includes the actual HTML tags (<p>, <b>), not just the text.
✅ 3. Getting Value of Form Elements (.val())
If you're working with form elements (like <input>, <textarea>, or <select>), you can use the
.val() method to get the current value of the element.

Example (Input Field):


<input type="text" id="inputField" value="Hello World!">
var inputValue = $("#inputField").val();
console.log(inputValue); // Output: "Hello World!"

Here, .val() retrieves the value of the input field, not the text inside it.

✅ 4. Getting Attribute Values (.attr())


You can also use .attr() to get the value of an attribute of an element. This is especially
useful for attributes like src, href, id, alt, and more.

Example:
<a id="link" href="https://example.com">Visit Example</a>
var hrefValue = $("#link").attr("href");
console.log(hrefValue); // Output: "https://example.com"

Here, .attr("href") retrieves the href attribute of the anchor <a> tag.

✅ 5. Getting CSS Property Value (.css())


You can use .css() to get the current value of a CSS property applied to an element.

Example:
<div id="box" style="width: 100px; height: 100px; background-color:
red;"></div>
var width = $("#box").css("width");
console.log(width); // Output: "100px"

Here, .css("width") retrieves the computed width of the #box element.

Updating elements with jQuery


Updating elements with jQuery is incredibly easy and allows for smooth interaction with the DOM.
1. Updating Text Content (.text())
You can update the text inside an element using the .text() method.

Example:
<p id="message">Old text</p>
<button id="changeText">Change Text</button>

<script>
$("#changeText").click(function() {
$("#message").text("New text!"); // Change the text of the <p>
});
</script>

When you click the button, the text inside the <p> element changes to "New text!".

✅ 2. Updating HTML Content (.html())


You can update the HTML inside an element using the .html() method. This allows you to
add or change HTML tags inside an element.

Example:
<div id="content">Old <b>bold</b> text</div>
<button id="changeHTML">Change HTML</button>

<script>
$("#changeHTML").click(function() {
$("#content").html("<i>New italic text</i>"); // Update with new HTML
});
</script>

When you click the button, the content of the <div> changes to "New italic text".

✅ 3. Updating the Value of Form Elements (.val())


For form elements like <input>, <select>, and <textarea>, you can update the value using
the .val() method.

Example (Input Field):


<input type="text" id="inputField" value="Old value">
<button id="updateValue">Update Value</button>

<script>
$("#updateValue").click(function() {
$("#inputField").val("New value"); // Set the new value of the input
field
});
</script>

When you click the button, the input field will display "New value".

✅ 4. Updating CSS Properties (.css())


You can update the CSS styles of an element using the .css() method.

Example:
<div id="box" style="width: 100px; height: 100px; background-color:
red;"></div>
<button id="changeStyle">Change Style</button>

<script>
$("#changeStyle").click(function() {
$("#box").css("background-color", "blue"); // Change background color to
blue
});
</script>

When you click the button, the background color of the #box element changes to blue.

✅ 5. Adding/Removing CSS Classes (.addClass(), .removeClass(),


.toggleClass())

You can add or remove CSS classes to/from elements to update their styling dynamically.

Example (Adding and Removing Classes):


<div id="box" class="redBox"></div>
<button id="toggleClass">Toggle Class</button>

<script>
$("#toggleClass").click(function() {
$("#box").toggleClass("blueBox"); // Toggle the blueBox class on and off
});
</script>

In this example:

 .addClass() adds a class to the element.


 .removeClass() removes a class from the element.
 .toggleClass() toggles between adding and removing a class.

✅ 6. Updating Attributes (.attr())


You can update the attributes of an element using the .attr() method.

Example (Updating href Attribute):


<a id="link" href="https://example.com">Go to Example</a>
<button id="updateLink">Update Link</button>

<script>
$("#updateLink").click(function() {
$("#link").attr("href", "https://newexample.com"); // Update href
attribute
});
</script>

When you click the button, the link’s href attribute will change to "https://newexample.com".

✅ 7. Appending and Prepending Content (.append(), .prepend())


You can add new content inside an element using .append() or .prepend().

 .append() adds content to the end of an element.


 .prepend() adds content to the beginning of an element.

Example:
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button id="addItem">Add Item</button>

<script>
$("#addItem").click(function() {
$("#list").append("<li>Item 3</li>"); // Add new item at the end of the
list
});
</script>

When you click the button, a new item will be added to the end of the list.

✅ 8. Removing Elements (.remove())


You can remove elements from the DOM with the .remove() method.

Example:
<p id="para">This is a paragraph</p>
<button id="removePara">Remove Paragraph</button>

<script>
$("#removePara").click(function() {
$("#para").remove(); // Remove the <p> element from the DOM
});
</script>

When you click the button, the paragraph is removed from the page.

🔑 Summary of Common Methods to Update Elements


Method Description Example
.text()
Update text content of an $("#para").text("New text");
element
.html()
Update HTML content $("#content").html("<b>New HTML</b>");
inside an element
.val()
Update value of form input $("#inputField").val("New Value");
elements
.css()
Update CSS properties of an $("#box").css("background-color",
element "blue");

.addClass()
Add a CSS class to an $("#box").addClass("highlighted");
element
.removeClass()
Remove a CSS class from an $("#box").removeClass("highlighted");
element
.attr()
Update the attribute value of $("#link").attr("href", "newLink.html");
an element
.append() Add content to the end of an $("#list").append("<li>New Item</li>");
Method Description Example
element
.prepend()
Add content to the beginning $("#list").prepend("<li>First
of an element Item</li>");

.remove()
Remove an element from the $("#para").remove();
DOM

Adding new content to an element using jQuery is simple and can be done in various ways.
Whether you're adding new HTML, text, elements, or attributes, jQuery provides methods
that make these operations smooth and flexible.

Common Methods to Add New Content in jQuery:

✅ 1. Adding Text (.text())


You can use the .text() method to add or change the text content inside an element.
However, note that it replaces the existing text, so you’ll need to append the new content.

Example (Appends Text):


<p id="message">This is the old text.</p>
<button id="addText">Add Text</button>

<script>
$("#addText").click(function() {
$("#message").text(function(index, currentText) {
return currentText + " Added text!"; // Append new text to current
content
});
});
</script>

Action: When you click the button, the existing text inside <p> will be updated to "This is the
old text. Added text!".

✅ 2. Adding HTML Content (.html())


The .html() method allows you to add HTML content to an element. It will replace the
existing HTML by default, but you can append to it as well.
Example (Appends HTML):
<div id="container">Current HTML content</div>
<button id="addHTML">Add HTML</button>

<script>
$("#addHTML").click(function() {
$("#container").append("<p>New HTML content added!</p>"); // Append new
HTML
});
</script>

Action: When you click the button, a new <p> element with "New HTML content added!"
will be appended inside the #container div.

✅ 3. Adding New Elements (.append(), .prepend(), .before(), .after())


You can add new elements inside or around an existing element using methods like .append(),
.prepend(), .before(), or .after().

 .append(): Adds content to the end of an element.


 .prepend(): Adds content to the beginning of an element.
 .before(): Adds content before the element.
 .after(): Adds content after the element.

Example (Using .append() to Add a New Element):


<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button id="addItem">Add Item</button>

<script>
$("#addItem").click(function() {
$("#list").append("<li>Item 3</li>"); // Add new list item at the end
});
</script>

Action: When you click the button, a new item "Item 3" is added to the end of the list.

In jQuery, getting and setting attributes of HTML elements is a straightforward task using the
.attr() method. It allows you to retrieve the value of an attribute or set a new value for an
attribute of an element.

Getting and Setting Attributes in jQuery


✅ 1. Getting Attributes
To retrieve the value of an attribute, you can use the .attr() method with only one argument:
the name of the attribute.

Example (Getting the href Attribute of a Link):


<a id="myLink" href="https://example.com">Click me!</a>
<button id="getLink">Get Link Attribute</button>

<script>
$("#getLink").click(function() {
var link = $("#myLink").attr("href"); // Get the href attribute
alert("The link is: " + link); // Display the href value
});
</script>

Action: When you click the button, an alert will display the current value of the href attribute,
which is "https://example.com".

✅ 2. Setting Attributes
To set or update the value of an attribute, use the .attr() method with two arguments: the
name of the attribute and the new value you want to set.

Example (Setting the href Attribute of a Link):


<a id="myLink" href="https://oldsite.com">Click me!</a>
<button id="setLink">Set New Link</button>

<script>
$("#setLink").click(function() {
$("#myLink").attr("href", "https://newsite.com"); // Set new href
attribute
});
</script>

Action: When you click the button, the href attribute of the link will change from
"https://oldsite.com" to "https://newsite.com".
In jQuery, you can easily get and set CSS properties using the .css() method. This method
allows you to work with the inline style of an element, and you can either retrieve the value of a
CSS property or apply a new value.

Here’s how you can get and set CSS properties using jQuery:

✅ 1. Getting CSS Properties


To retrieve the value of a CSS property, pass the property name as a string to the .css()
method.

Example (Getting the background-color of an Element):

<div id="box" style="background-color: blue; width: 200px; height: 200px;">


This is a box.
</div>
<button id="getColor">Get Background Color</button>

<script>
$("#getColor").click(function() {
var color = $("#box").css("background-color"); // Get the background
color
alert("The background color is: " + color); // Show the color in an
alert
});
</script>

Action: When you click the button, it will show an alert with the current background color of the
#box element.

✅ 2. Setting CSS Properties


To set or modify a CSS property, pass the property name and value to the .css() method. You
can also set multiple properties at once by passing an object with property-value pairs.

Example (Setting the background-color and width of an Element):


<div id="box" style="background-color: blue; width: 200px; height: 200px;">
This is a box.
</div>
<button id="changeColor">Change Background Color</button>

<script>
$("#changeColor").click(function() {
$("#box").css("background-color", "red"); // Set the background color to
red
$("#box").css("width", "300px"); // Set the width to 300px
});
</script>

Action: When you click the button, the background-color of the #box will change to red, and
the width will be updated to 300px.

In jQuery, the .each() method is a utility function that allows you to iterate over a collection of
elements and execute a function for each one. It is often used when you want to apply some
operation to each element in a set, whether you're modifying content, handling events, or
changing styles.

Syntax:
javascript
CopyEdit
$(selector).each(function(index, element) {
// Code to execute for each element
});

 index: The index of the current element in the collection (starting from 0).
 element: The current element in the iteration, which you can use to manipulate it.

✅ 1. Basic Example with .each()


Let's start with a simple example where we iterate over a set of elements and change their text
content.

Example (Change Text for Each List Item):


<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<button id="changeText">Change Text</button>

<script>
$("#changeText").click(function() {
$("li").each(function(index) {
$(this).text("Item " + (index + 1) + " has been updated.");
});
});
</script>
Action: When you click the "Change Text" button, the text of each list item will be updated to
"Item X has been updated." where X is the index of the item.

In jQuery, events are actions that occur in the browser, such as a user clicking a button, moving
the mouse, or typing in an input field. You can listen for these events and respond with custom
functions. jQuery simplifies working with events by offering cross-browser compatibility and
concise syntax for attaching event handlers.

✅ 1. Basic Syntax for Handling Events


The basic syntax for event handling in jQuery is as follows:

javascript
CopyEdit
$(selector).event(function() {
// Code to execute when the event occurs
});

 selector: The element you want to attach the event to.


 event: The type of event (e.g., click, hover, keydown).
 function: The callback function to execute when the event is triggered.

✅ 2. Common jQuery Event Methods


Here are some common events you can use in jQuery:

1. click

The click event is triggered when an element is clicked.

Example (Click Event):


<button id="clickMe">Click Me</button>
<script>
$("#clickMe").click(function() {
alert("Button was clicked!");
});
</script>

Action: When the button is clicked, an alert will pop up with the message "Button was
clicked!".
2. mouseenter / mouseleave

The mouseenter and mouseleave events are triggered when the mouse enters or leaves an
element.

Example (Mouseenter and Mouseleave):


<div id="box" style="width: 200px; height: 200px; background-color:
lightblue;">
Hover over me!
</div>

<script>
$("#box").mouseenter(function() {
$(this).css("background-color", "orange"); // Change color when mouse
enters
});

$("#box").mouseleave(function() {
$(this).css("background-color", "lightblue"); // Change color when mouse
leaves
});
</script>

Action: When you hover over the div, its background color will change to orange, and when the
mouse leaves, it will return to lightblue.

3. keydown / keyup

The keydown and keyup events are triggered when a key is pressed down or released,
respectively.

Example (Keydown Event):


<input type="text" id="inputField" placeholder="Type something">
<script>
$("#inputField").keydown(function() {
alert("A key was pressed!");
});
</script>

Action: When a key is pressed while focused on the input field, an alert will pop up with the
message "A key was pressed!".

4. submit

The submit event is triggered when a form is submitted.

Example (Form Submit):


<form id="myForm">
<input type="text" name="username" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<script>
$("#myForm").submit(function(event) {
event.preventDefault(); // Prevents the default form submission
alert("Form submitted!");
});
</script>

Action: When the form is submitted, an alert will pop up with the message "Form submitted!",
and the default form submission behavior will be prevented.

EVENT OBJECT

In jQuery, the event object is passed to the event handler function whenever an event occurs. It
contains information and methods related to the event, such as the event type, the target element,
mouse position (for mouse events), key pressed (for keyboard events), and much more.

📌 Syntax:
javascript
CopyEdit
$(selector).on("event", function(event){
// use event object here
});

✅ Example:
<button id="myBtn">Click me</button>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$("#myBtn").on("click", function(event){
console.log("Event type: " + event.type); // e.g., "click"
console.log("Target element: ", event.target); // the button
console.log("Which key/button: " + event.which); // mouse button or key
code
console.log("Event pageX: " + event.pageX); // x-coordinate on the
page
});
</script>

🔍 Common Properties of event object in jQuery:

Property Description
event.type The type of the event (e.g., "click", "keydown")
Property Description
event.target The DOM element that triggered the event
event.currentTarget The element to which the event handler is attached
event.pageX The mouse position relative to the document
event.pageY Same as above, for Y-axis
event.which The button or key that was pressed
event.preventDefault() Prevents the default action
event.stopPropagation() Stops the event from bubbling up

EFFECTS

In jQuery, effects refer to built-in methods that help you create visual animations like showing, hiding,
fading, sliding elements, etc., with minimal code.

Basic Effects

Method Description

show() Displays the selected element(s)

hide() Hides the selected element(s)

toggle() Toggles between show() and hide()

Example:
$("#btn").click(function(){
$("#box").toggle();
});

🌫 Fade Effects

Method Description

fadeIn() Fades in a hidden element

fadeOut() Fades out a visible element

fadeToggle() Toggles between fadeIn() and fadeOut()

fadeTo(speed, opacity) Fades the element to a specific opacity


Example:
$("#btn").click(function(){
$("#box").fadeOut("slow");
});

🎢 Slide Effects

Method Description

slideDown() Slides down a hidden element

slideUp() Slides up a visible element

slideToggle() Toggles between slideDown() and slideUp()

Example:
$("#btn").click(function(){
$("#box").slideToggle("fast");
});

🛠 Custom Animation

Use animate() to perform custom animations.

$("#box").animate({
left: '250px',
opacity: '0.5',
height: 'toggle'
}, 1000); // duration in milliseconds

⏱ Speed Options

 "slow" (~600ms)
 "fast" (~200ms)
 Or any number in milliseconds: 1000, 1500, etc.

Animating CSS properties


In jQuery, you can animate CSS properties using the .animate() method. This method allows
you to create custom animations by gradually changing CSS property values over time.

Basic Syntax:
$(selector).animate({properties}, duration, easing, callback);

Example 1: Animate Width and Height

<div id="box" style="width:100px; height:100px; background:red;"></div>

<script>

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

$(this).animate({

width: "200px",

height: "200px"

}, 1000); // 1000 ms = 1 second

});

</script>

Notes:

 Only numeric properties can be animated (e.g., width, height, left, opacity).
 Non-numeric properties like background-color require jQuery UI or other plugins.
 The duration can be a number in milliseconds or strings like "slow" or "fast".
 You can chain .animate() calls for multiple animations.

Traversing the DOM

DOM traversal in jQuery means moving through (or “navigating”) the elements in the HTML document
— up, down, and sideways in the DOM tree. jQuery makes this super easy with a set of traversal
methods.

Upward Traversal (Ancestors)


.parent()

Gets the immediate parent.

Example

$(this).parent();
.parents()

Gets all ancestors, optionally filtered.

Example

$(this).parents(); // all ancestors

$(this).parents("div"); // all ancestor divs

.closest()

Finds the nearest ancestor that matches the selector.

Example

$(this).closest(".container");

Downward Traversal (Descendants)


.children()

Gets direct children.

$("#main").children();

$("#main").children(".item"); // only those with class "item"

.find()

Gets all descendants matching a selector.

$("#main").find("p"); // finds all <p> inside #main

Working with forms


Working with forms in jQuery is super handy — you can easily get/set values, validate input, respond to
user actions, and submit forms with AJAX if needed.

1. Selecting Form Elements


$("input") // selects all input fields
$("input:text") // only text inputs
$("input:radio") // radio buttons
$("input:checkbox") // checkboxes
$("select") // dropdowns
$("textarea") // textarea
📝 2. Getting & Setting Values
Text input / textarea / select:

// Get value
let name = $("#name").val();

// Set value
$("#name").val("John Doe");

Checkbox / radio:
// Check if checked
let isChecked = $("#check1").is(":checked");

// Check it
$("#check1").prop("checked", true);

// Uncheck
$("#check1").prop("checked", false);

🔄 3. Form Submission
Basic submit event:
$("#myForm").submit(function(e) {
e.preventDefault(); // prevent actual submission
alert("Form submitted!");
});

Javascript Libraries
JavaScript libraries are pre-written JavaScript code that help you perform common tasks faster and
easier — like DOM manipulation, animations, AJAX calls, form validation, and more. Here’s a list of
popular and widely-used JavaScript libraries, grouped by their purpose:

1. DOM Manipulation & Utilities


🔹 jQuery

Still used in many projects for simpler syntax and cross-browser support.
2. UI & Animation
🔹 GSAP (GreenSock Animation Platform)

For powerful, smooth animations.

Anime.js

Lightweight animation library (good for SVG, CSS, DOM animations).

3. Charts & Graphs


🔹 Chart.js

Simple and flexible for bar, line, pie charts, etc.

D3.js

Powerful data visualization (steeper learning curve).

4. Form Validation
🔹 Validator.js

Useful for custom validations in JavaScript.

Parsley.js

Easy client-side form validation with built-in rules.

5. AJAX / HTTP Requests


🔹 Axios

Promise-based HTTP client (more modern than jQuery’s $.ajax()).

jQuery and Ajax


jQuery makes working with AJAX much easier and more readable by providing simple methods
to send and receive data from a server without needing to reload the entire web page. This is
particularly useful when you want to update a part of your website dynamically. One of the
simplest jQuery methods is .load(), which loads content from a server into a selected HTML
element. For more control, jQuery offers .get() and .post() methods, which allow you to send
GET and POST requests respectively, and handle the server's response with callback functions.
For full flexibility, the $.ajax() method can be used. It allows you to specify the request type,
data to be sent, success and error callbacks, and more.

For example, if you have a form and want to submit it without refreshing the page, you can use
jQuery to capture the form submission event, prevent the default behavior using
e.preventDefault(), collect form data using .val(), and send it to the server using $.ajax().
Once the server responds, you can update the HTML content of a specific element using
.html() or display a message accordingly. This technique is widely used in modern web
development to create a smoother and more interactive user experience.

You might also like