UNIT-4
jQuery
Introduction to jQuery
• jQuery is a fast and concise JavaScript Library with a nice motto Write less, do
more.
• It takes a lot of common tasks that requires many lines of JavaScript code to
accomplish, and binds them into methods that can be called with a single of code
whenever needed.
• jQuery is an open-source JavaScript library that simplifies the interactions between
an HTML/CSS document, or more precisely the Document Object Model (DOM).
jQuery simplifies HTML document traversing and manipulation, browser event
handling, DOM animations, Ajax interactions, and cross-browser JavaScript
development.
Contd.
• Before you can start studying jQuery, you should have a basic
knowledge of: HTML, CSS, JavaScript.
• Many of the biggest companies on the Web use jQuery, such as:
• Google
• Microsoft
• Ibm
• Netflix
What can jQuery do?
• Find things on the page (like buttons or pictures)
• Change colors, hide or show things
• Make things move (animations!)
• Help websites load things fast without refreshing
• Work on all web browsers without problems
Difference Between JavaScript and jQuery
Feature JavaScript jQuery
A programming language A library built on JavaScript
Definition
used for web development to make coding easier
Code Length Longer and more complex Shorter and simpler
Requires more lines of code Uses simple methods to do
Ease of Use
to perform tasks the same tasks
Cross-Browser May need extra code for Handles cross-browser issues
Compatibility different browsers automatically
Built-in functions for
Animations & Effects Requires manual coding
animations
Example: Hiding a Button on Click
Using JavaScript:
document.getElementById("myButton").addEventListener("click",
function() {
document.getElementById("myText").style.display = "none";
});
Note:
Using jQuery:
$(document).ready(function(){ •For large, modern projects → JavaScript
$("#myButton").click(function(){ •For quick, easy web effects → jQuery
$("#myText").hide();
});
});
How to Add jQuery to HTML Page?
• There are two ways to use jQuery in your HTML page.
1. Download the jQuery library from jQuery.com
2. Include jQuery from a CDN, like Google.
Download the jQuery Files Locally and use Them
• Visit the jQuery Official Website and download the latest version of jQuery. Then
include the downloaded jQuery file into your project. Place the jquery.min.js file
in a directory within your project, such as js/. Next, use <script> tag inside the
<head> section to add jQuery file into your web page.
Contd.
Syntax:
<script src="js/jquery.min.js"></script>
2. Using jQuery from CDN Link
•The easiest method to include jQuery in your HTML page is by using a CDN link.
CDN links hosted the jQuery files to the servers that can be easily used without
downloading the files.
•Include jQuery CDN link to the HTML page using <script> tag inside the head
section of the page.
Syntax:
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
Popular CDNs for jQuery include:
1. Google CDN:
https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js
2. Microsoft CDN:
https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.min.js
3. CDN JS:
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js
Basic Syntax for jQuery Function
• In jQuery, the syntax for selecting and manipulating HTML elements is written as:
$(selector).action()
• A $ sign to define/access jQuery
• A (selector) to "query (or find)" HTML elements. The selector can be any valid CSS selector, such as a class,
ID, or tag name.
• A jQuery action() to be performed on the elements. Common actions include manipulating CSS properties,
handling events, or performing animations.
• Note: A jQuery statement typically starts with the dollar sign($) and ends with a semicolon(;).
Contd.
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".
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: $().
• Syntax: Following is the syntax of how to use a selector in jQuery:
$(selector).action()
Types of jQuery Selectors
1. Basic Selectors
2. Hierarchy Selectors
3. Attribute Selectors
4. Filter Selectors
5. Form Selectors
Basic Selectors
1. Tag Name:
•Represents a tag name available in the DOM. For example $('p')
selects all paragraphs <p> in the document.
2. Tag ID:
•Represents a tag available with the given ID in the DOM. For example
$('#some-id') selects the single element in the document that has an ID
of some-id.
3. Tag Class:
•Represents a tag available with the given class in the DOM. For
example $('.some-class') selects all elements in the document that have
a class of some-class.
Contd.
4. Universal(*):
•It selects all elements available in a DOM.
5. Multiple Elements A,B,C:
•It selects the combined results of all the specified selectors A,B and C.
Basic Example for jQuery
Selectors
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Selectors</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
Contd.
<body>
<h1>Rajiv Gandhi University of Knowledge Technologies, Rk
VAlley</h1>
<h2>Branches</h2>
<p id="cse">Computer science and Engineering</p>
<p id="ece">Electrical and Electronics Enginering</p>
<p id="civil">Civil Engineering</p>
<p class="text">Hello Good morning everyone</p>
<button id="hidebtn">click me</button>
Contd.
<script>
$(document).ready(function() {
$('#cse').css('color','red'); // Select by ID
$('#ece').css('color','red'); // Select by ID
$('.text').css('color','green'); //Select by Class
$('*').css('color','red');
Contd.
$('#ece,.text,button').css('color','blue'); // Applying multiple selectors
$('#hidebtn').click(function(){ //Button click to toggle paragraphs with animation
$('p').toggle(); // hide/show effect
});
});
</script>
</body>
</html>
jQuery Attributes
• Attributes store additional information about HTML elements.
• Common HTML attributes: href, src, alt, title, id, class, value, etc.
• jQuery provides methods to get, set, and remove attributes
dynamically.
• Key benefits:
✅ Easy manipulation of attributes
✅ Efficient DOM updates
✅ Simplifies interactive web development
jQuery Attribute Methods
Method Description Example
attr() Gets or sets an attribute $("img").attr("src")
removeAttr() Removes an attribute $
("input").removeAttr("disable
d")
prop() Gets or sets properties $
(e.g., checked, disabled) ("#checkbox").prop("checked
", true)
val() Gets or sets the value of
$("input").val("New Value")
input fields
Contd.
1. attr() Method
Used to get or set the value of an attribute.
Syntax:
$(selector).attr(attributeName);
$(selector).attr(attributeName, value);
Example:
$("#myLink").attr("href", "https://www.google.com");
Contd.
2. removeAttr() Method
Removes an attribute from the selected element.
Syntax:
$(selector).removeAttr(attributeName);
Example:
$("#myImage").removeAttr("alt");
Contd.
3. prop() Method
Used to get or set properties (boolean attributes like checked, disabled,
etc.).
Syntax:
$(selector).prop(propertyName);
$(selector).prop(propertyName, value);
Example:
$("#myCheckbox").prop("checked", true);
Contd.
4. val() Method
Used to get or set the value of form elements.
Syntax:
$(selector).val();
$(selector).val(value);
Example:
$("#myInput").val("Hello World");
Contd.
5. html() Method
Used to get or set the HTML content inside an element.
Syntax:
$(selector).html();
$(selector).html(value);
Example:
$("#myDiv").html("<b>Bold Text</b>");
Contd.
6. text() Method
Used to get or set the text content inside an element.
Syntax:
$(selector).text();
$(selector).text(value);
Example:
$("#myParagraph").text("Hello, World!");
Basic Example for jQuery
Attributes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple jQuery Attribute Methods</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js">
</script>
Contd.
<style>
.disabled {
pointer-events: none; /* Makes the link unclickable */
color: gray;
}
</style>
Contd.
<script>
$(document).ready(function(){
// Change the link URL
$("#changeLink").click(function(){
$("#myLink").attr("href", "https://google.com").text("Go to
Google");
});
Contd.
// Remove the hyperlink
$("#removeLink").click(function(){
$("#myLink").removeAttr("href").text("Link Removed");
});
// Disable the link (prevent clicking)
$("#disableLink").click(function(){
$("#myLink").addClass("disabled");
});
Contd.
// Enable the link (allow clicking again)
$("#enableLink").click(function(){
$("#myLink").removeClass("disabled");
});
// Get input box value
$("#getValue").click(function(){
let value = $("#myInput").val();
$("#displayValue").text("You entered: " + value);
});
Contd.
// Set input box value
$("#setValue").click(function(){
$("#myInput").val("Hello, jQuery!");
});
});
</script>
</head>
Contd.
<body>
<!-- Link Example -->
<a id="myLink" href="https://facebook.com">VisitFacebook</a>
<br><br>
<button id="changeLink">Change Link</button>
<button id="removeLink">Remove Link</button>
<button id="disableLink">Disable Link</button>
<button id="enableLink">Enable Link</button>
<br><br>
Contd.
<!-- Input Box Example -->
<input type="text" id="myInput" placeholder="Enter text here">
<button id="getValue">Get Value</button>
<button id="setValue">Set Value</button>
<p id="displayValue" style="font-weight: bold; color: blue;"></p>
</body>
</html>
Event Handling in jQuery
Understanding how to handle events
using jQuery
Introduction to jQuery Events
• An Event is something that happens when user interact with the webpage, such as when
he clicked a link or button, pressed a key on the keyboard, moved the mouse pointer etc.
• A jQuery Event is the result of an action that can be detected by jQuery (JavaScript).
When these events are triggered, you can then use a custom function to do pretty much
whatever you want with the event. These custom functions are called Event Handlers.
• The jQuery library provides methods to handle all the DOM events and make complete
event handling considerably easier than what we have available in JavaScript.
Contd.
Following are the examples of some common events −
•A mouse click
•A web page loading
•Taking mouse over an element
•Submitting an HTML form
•A keystroke on your keyboard, etc.
• When an event is triggered Event Handler is called
Example: JavaScript vs jQuery
JavaScript:
document.getElementById("btn").addEventListener("click", function()
{
alert("Button clicked!");
});
jQuery:
$("#btn").click(function() {
alert("Button clicked!");
});
Different Types of jQuery Events
The following table lists some of the important DOM events.
Window/Document
Mouse Events Keyboard Events Form Events
Events
click keypress submit load
dblclick keydown change resize
hover keyup select scroll
mousedown blur unload
mouseup focusin ready
What is jQuery Event Handling?
• jQuery provides a simpler and more efficient way to handle events
compared to vanilla JavaScript.
• It offers built-in methods to attach event listeners to elements.
• It ensures cross-browser compatibility and supports event delegation.
Basic Example: Click Event
$(document).ready(function() {
$("button").click(function() {
alert("Button clicked!");
});
});
Contd.
Two ways to bind an event to an element:
•Using bind()
$(selector).bind(eventType,eventData,handlerFunction);
eventType: The javaScript event type. E.g.: click, hover,
keydown, etc.
eventData: The data to be passed to event handler
function, if any.
handlerFunction: The operation to execute each time the
event is fired.
Contd.
• Using event method directly
$(selector).click(handlerFunction);
$(selector).hover(handlerFunction);
• Removing event handlers
$(selector).unbind(eventType,handlerFunction);
Advantages of jQuery Event Handling
• Simplifies event binding with short and readable syntax.
• Prevents repetition by applying events to multiple elements at once.
• Supports event delegation (.on()) for dynamically added elements.
• Cross-browser compatibility ensures smooth execution.
Mouse Events in jQuery
Mouse Events: Events that occurs when the mouse interacts with the HTML
Document.
•click() - When an element is clicked.
• dblclick() - When an element is double-clicked.
• mousedown() - When the mouse button is pressed.
• mouseup() - When the mouse button is released.
• hover() - When mouse enters or leaves an element.
Keyboard Events in jQuery
Keyboard Events: The key Events happens whenever a user interacts
with keyboard.
• keydown() – This Event fires when the user is pressing a key.
• keyup() - This Event fires when the user releases the key
• keypress() – This Event fires when the user pressed the key
Form Events in jQuery
Form Events: Events that occur through the interaction of a user with
an HTML Form are called jQuery form Events.
• focus() - When an input field is focused.
• blur() - When an input field loses focus.
• change() - When the value of an input field changes.
• submit() - When a form is submitted.
Document & Window Events
Events triggered for the window object (applies to the <body> tag).
• ready() - When the document is fully loaded.
• scroll() - When the page is scrolled.
• resize() - When the browser window is resized.
Introduction to jQuery Style Methods
• jQuery provides powerful methods to manipulate CSS styles
dynamically.
• Commonly used for adding, removing, or toggling styles.
• Helps improve UI/UX in web applications.
Common jQuery Style Methods
1. .css() – Get or set CSS properties.
2. .addClass() – Add one or more classes.
3. .removeClass() – Remove one or more classes.
4. .toggleClass() – Toggle between adding and removing a class.
5. .height() / .width() – Get or set the height/width of an element.
Contd.
1. .css() – Get or Set CSS Properties
The .css() method can be used to get or set CSS properties.
Example: Set CSS Properties
$("p").css("color", "red");
$("p").css({"font-size": "18px", "background-color": "yellow"});
Example: Get a CSS Property
let color = $("p").css("color");
console.log(color);
Contd.
2. .addClass() – Add CSS Classes
Adds one or more classes to an element.
Example:
$("p").addClass("highlight");
3. .removeClass() – Remove CSS Classes
Removes one or more classes from an element.
Example:
$("p").removeClass("highlight");
Contd.
4. .height() / .width() – Get or Set Element Size
These methods help in retrieving or modifying the dimensions of an
element.
Example:
$("div").height(200); // Set height
$("div").width(300); // Set width
let divHeight = $("div").height(); // Get height
console.log(divHeight);
Contd.
5. .toggleClass() – Toggle CSS Classes
Adds the class if it is not present; removes it if it is present.
Example:
$("p").toggleClass("highlight");
jQuery Effects
• jQuery provides a powerful set of effects that allow you to enhance
the visual appearance of your web page dynamically. These effects
help you create animations, hide/show elements, and apply different
styles with smooth transitions. These are the different jQuery Effects:
1.Hide and Show
2.Fading Effects
3.Sliding Effects
4.Chaining Effects
5.Delay Effect
Contd.
Effects:
Effects
DISPLAY FADING SLIDING OTHER
fadeIn
slideDown
hide fadeout
SlideUp Animate
show fadeToggl
slideToggle delay
toggle e
fadeTo
Contd.
1. Hide and Show
These methods allow elements to be hidden or displayed dynamically.
$("p").hide(); // Hides the paragraph
$("p").show(); // Shows the paragraph
$("p").toggle(); //Hide/show the paragraph
2. Delay Effect
Delays the execution of the next jQuery method.
$("p").fadeOut(2000).delay(1000).fadeIn(2000);
Contd.
3. Fading Effects
Fading effects allow elements to fade in and out smoothly.
$("p").fadeIn(); // Gradually appears
$("p").fadeOut(); // Gradually disappears
$("p").fadeToggle(); // Toggles between fadeIn and fadeOut
$("p").fadeTo(2000, 0.5); // Fades to 50% opacity over 2 seconds
Contd.
4. Sliding Effects
Sliding effects create a smooth vertical slide transition.
$("p").slideDown(); // Slides down
$("p").slideUp(); // Slides up
$("p").slideToggle(); // Toggles between slideDown and slideUp
5. Chaining Effects
You can chain multiple effects together.
$("div").slideUp(1000).slideDown(1000).fadeOut(1000).fadeIn(1000);
Traversing the DOM in
jQuery
Understanding DOM Navigation and Filtering Methods
What is Traversing?
• DOM Traversal in jQuery means navigating (moving) through the
HTML structure to find, select, or manipulate elements. The DOM
(Document Object Model) represents the structure of a webpage as a
tree with parents, children, and siblings.
• The image 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.
<div>
<ul>
<li> <li>
<span> <span> <b>
Illustration explained:
•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>
Contd.
• 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.
Introduction to jQuery DOM Traversing
• jQuery provides powerful methods to traverse the DOM tree.
• It allows moving up (Ancestors), down (Descendants), and sideways
(Siblings).
Moving Up the DOM (Ancestors)
• .parent() - Selects immediate parent
• .parents() - Selects all ancestors
• .parentsUntil(selector) - Select Ancestors Until a Specified Element.
Syntax:
$(selector).parent();
$(selector).parents();
$(selector).parentsUntil(selector);
Moving Down the DOM (Descendants)
• .children() - Selects direct children
• .find(selector) - Finds all descendants that match the selector
Syntax:
$(selector).children();
$(selector).find("childSelector");
Moving Sideways in the DOM (Siblings)
• .siblings() - Selects all siblings
• .next() - Selects the next sibling
• .prev() - Selects the previous sibling
• .nextAll() - Selects all next siblings
• .prevAll() - Selects all previous siblings
Syntax:
$(selector).siblings();
$(selector).nextAll();
$(selector).prevAll();
$(selector).next();
$(selector).prev();
Filtering Methods in jQuery
• .first() - Selects the first element
• .last() - Selects the last element
• .eq(index) - Selects an element by index
• .filter(selector) - Filters elements that match the selector
• .not(selector) - Excludes elements that match the selector
Syntax:
$(selector).first();
$(selector).last();
$(selector).eq(index);
$(selector).filter(selector);
$(selector).not(selector);
Chaining Traversal Methods
• You can combine multiple traversal methods:
• $('p').parent().next().children('.text').css('color', 'red');
• - Moves to parent
• - Moves to next sibling
• - Finds children with class .text
• - Changes text color to red
Introduction to jQuery plugins
• A jQuery plugin is a reusable piece of code that extends the
functionality of jQuery. It allows developers to encapsulate a specific
functionality into a separate module, making it easy to reuse across
different projects. jQuery plugins help in simplifying common tasks
such as animations, form validation, image sliders, and more.
Why Use jQuery Plugins?
• Code Reusability – Plugins allow developers to write once and use
multiple times.
• Simplicity – They simplify complex tasks with minimal coding.
• Consistency – Using well-maintained plugins ensures consistent
behavior across different browsers.
• Community Support – jQuery has a vast ecosystem with many open-
source plugins.
• Performance Optimization – Plugins are often optimized for better
performance.
How to Use a jQuery Plugin?
• To use a jQuery plugin, follow these steps:
• Include jQuery Library:
• Before using any plugin, include the jQuery library in your HTML
file.
<script src="https://code.jquery.co m/jquery-3.6.0.min.js"></script>
• Include the Plugin:
• Download or link to a plugin file.
• You can download jQuery plug-in from https://jquery.com/plugins
<script src="path-to-plugin.js"></script>
How to create a jQuery plugin with
methods
In Jquery Plug-in is a code that is needed in a standard javascript file.
Plugins help in providing different methods that can be used with
different jquery library methods.
Create a method:
jQuery.fn.methodName = methodDefinition;
<>pNote: Where .methodName is the name of a method and
methodDefinition defines a method
Contd.
Create the Plugin
This part defines the plugin:
(function($) {
$.fn.changeColor = function(options) {
var settings = $.extend({
color: "blue" // Default color
}, options);
return this.css("color", settings.color);
};
}(jQuery));
Contd.
Initialize (Call) the Plugin:
•Now, we use the plugin to change text color.
$(document).ready(function(){
$(".text").changeColor({ color: "red" });
});
Creating a jQuery Plugin for Text Color
Change
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>With jQuery Plugin</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
Contd.
<body>
<p class="text">Hello, this is a sample text.</p>
<button class="changeColorBtn">Change Color</button>
<p class="text">Another text to change.</p>
<button class="changeColorBtn">Change Color</button>
Contd.
<script>
(function($) {
jQuery.fn.changeColor = function(options) {
var settings = $.extend({
color: "blue"
}, options);
return this.css("color", settings.color);
};
}(jQuery));
Contd.
$(document).ready(function(){
$(".changeColorBtn").click(function(){
$(this).prev(".text").changeColor({ color: "red" });
});
});
</script>
</body>
</html>