KEMBAR78
JQuery Interview | PDF | J Query | Document Object Model
0% found this document useful (0 votes)
17 views387 pages

JQuery Interview

jQuery is a lightweight JavaScript library designed to simplify HTML client-side scripting, making tasks like DOM manipulation, event handling, and AJAX easier. Created by John Resig in 2006, it is widely used across popular websites due to its efficiency and ease of use. The document also discusses the jQuery ID selector, its syntax, and advantages over vanilla JavaScript methods.

Uploaded by

Prabin Magar
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)
17 views387 pages

JQuery Interview

jQuery is a lightweight JavaScript library designed to simplify HTML client-side scripting, making tasks like DOM manipulation, event handling, and AJAX easier. Created by John Resig in 2006, it is widely used across popular websites due to its efficiency and ease of use. The document also discusses the jQuery ID selector, its syntax, and advantages over vanilla JavaScript methods.

Uploaded by

Prabin Magar
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/ 387

Introduction to jQuery | What is, why, and how to use jQuery

What is jQuery?
1. jQuery is a fast, small, lightweight, and feature-rich JavaScript library. It is designed
to simplify the client-side scripting of HTML. It makes things like DOM traversal and
manipulation, event handling, animation, and Ajax much simpler. With a combination
of versatility and extensibility, jQuery has changed the way that millions of people
write JavaScript. As of May 2019, jQuery was used by 73% of the 10 million most
popular websites.
2. jQuery was created by John Resig in 2006 with the motto “Write less, do more”.
3. The main purpose of jQuery is to make JavaScript faster, easier, more concise, more
effective, and more attractive. jQuery helps the developers to make websites more
dynamic and interactive with jQuery.
4. jQuery takes a lot of common functionalities of Vanilla JavaScript which required
many lines of code and wraps them into pre-defined and built-in methods which you
can call in a single line of code in jQuery.
Why jQuery?
jQuery Syntax is designed to make it easier to achieve a wide collection of functionalities.
Let us now see one by one, why we should learn jQuery and use it over vanilla JavaScript.
1. LIGHT-WEIGHT: jQuery is a very lightweight library of JavaScript. Its minified file is
just about 19 kB.
2. SHORT SELECTORS: jQuery provides us a shorter syntax to select any element of
our DOM (Document Object Model). Thus, using jQuery, we can easily target any of
the DOM elements
3. DOM MANIPULATION: jQuery makes the DOM manipulating really with short and
simple syntax by its selector engine named Sizzle.
4. DOM TRAVERSING: jQuery provides us built-in and predefined keywords to traverse
through the DOM, which is really hassle-free for the developers.
5. EVENT HANDLING: jQuery provides us an extremely easy and elegant way to
Handle any keyboard or mouse event in our web application such as clicking on a
button or pressing the enter key or firing the blur event.
6. AJAX SUPPORT: jQuery helps us to develop dynamic and interactive web
applications with the latest AJAX technology. AJAX calling with jQuery is much easier
than vanilla JavaScript.
7. ANIMATION: jQuery has a sea of built-in animation effects that can provide your
website an elegant look.
8. PLUG-INS: jQuery provides a lot of plug-ins to use in our web applications to make
high-level effects, advanced and themeable widgets
9. CROSS-BROWSER SUPPORT: JQuery has cross-browser support, works efficiently
in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome, and Opera 9.0+.
Syntax to use jQuery:
jQuery has a very basic syntax to perform any functionalities
Basic syntax is: $(selector).action();
1. The $ sign is to define/access jQuery
2. (selector) is the query for any DOM elements. jQuery uses CSS selectors here
3. Action() is the jQuery handler to perform any functionality to the selected DOM
element
The $(document).ready(handler); — This statement is typically known as ready event.
Where the handler is basically a function that is passed to the ready() method to be
executed safely as soon as the document is ready to be manipulated i.e. when the DOM
hierarchy has been fully constructed.
Now let us see a very short example of jQuery and look at how jQuery is simpler and
shorter than JavaScript
Example without using jQuery: Suppose we have to change the color of a div element
by clicking a button. At first, let’s see how we can achieve that with JavaScript
<h1>Example</h1>
<div class="test">
<p>Click on the button to change the color</p>
</div>
<button type="button" id="demo">Change Color</button>

<script>
const btn = document.getElementById("demo");
const div = document.querySelector('.test');
btn.addEventListener("click", function () {
div.style.backgroundColor = "#86f2f7";
})
</script>
After clicking the ‘Change Color’ button, it will change the background color of the div
element as shown in the below image.

Example using jQuery: Now let us see, how this can be achieved by jQuery in just one
line of code as shown in the below example.
<h1>Example</h1>
<div class="test">
<p>Click on the button to change the color</p>
</div>
<button id="demo">Change Color</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('.test').css('backgroundColor', '#86f2f7');
});
});
</script>
Note: You might have noticed that our jQuery codes in the example are inside the
document-ready event. This is to prevent any jQuery code from running before the
document is finished loading (is ready). We will discuss the document-ready event
elaborately in our next article.
$(document).ready() function in jQuery
What is $(document).ready() function in jQuery?
$(document).ready() is an event in jQuery that is fired only when the whole DOM is fully
loaded and ready to be manipulated by jQuery. This document.ready event is to prevent
any jQuery code from running before the document is finished loading (is ready). This is
the earliest safe point of the page loading process where we can manipulate our DOM
elements. This allows you to write your jQuery (or JavaScript) code before the body tag.
Note: The document.ready event fires just after the DOM is loaded but before all the
images, CSS, frames, etc are fully loaded.
Following is the syntax to use $(document).ready()

Now let us see these things by practical examples of how this event works actually.
<h1>$(document).ready() event in jQuery</h1>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
alert("Button is Clicked");
});
});
</script>
<button id="demo">Click Me</button>
Now, click on the Click Me button and it will give you the following alter box.

As you can see, in our example, our code is wrapped inside the $(document).ready().
Also, notice that our button element is placed at bottom of our script. But that is working
perfectly fine as document ready event has not fired until the DOM elements are fully
loaded. But what if we remove that $(document).ready() from our code as shown in the
below example.
<h1>$(document).ready() event in jQuery</h1>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$('#demo').click(function () {
alert("Button is Clicked");
});
</script>
<button id="demo">Click Me</button>
Now, with the above changes in place, run the code and you will get the following page
and click on the Click Me button.

Here nothing is occurring when we are clicking the button because in this case when our
code is executing, our script tag is at the top of the button element so our script is
executing before the button element is loaded. So, our selector is unable to find
“#demo”.
But if we put our script code after the button element as shown in the below example,
then our output will be OK and fine. Because by the time of executing our script, the
button element is loaded.
<h1>$(document).ready() event in jQuery</h1>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$('#demo').click(function () {
alert("Button is Clicked");
});

</script>
jQuery CDN
jQuery CDN | Content Delivery Network
1. What is CDN?
2. Advantages and Disadvantages of Using CDN
3. What if the jQuery files cannot be downloaded from the CDN?
What is CDN?
CDN stands for Content Delivery Network. A CDN is a system of distributed servers that
host resources like images, CSS, JavaScript files, etc. Giant companies like Google,
Microsoft, Yahoo provide a free public CDN from which we can load jQuery instead of
hosting it in our own web server.
GOOGLE CDN:
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js”></script>
MICROSOFT CDN:
<script src=”https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.min.js”></script>
Advantages of Using CDN:
1. HIGH-CAPACITY INFRASTRUCTURES: Google, Microsoft, Yahoo provides great
capacity and high scalability. The better CDNs offer higher availability and lower
network latency.
2. DISTRIBUTED CDN SERVERS: When a user requests for a web page or a file the
CDN server closest to that user is dynamically determined and is used to deliver the
content to the user therefore speed of delivery increases.
3. BROWSER PRE-CACHING: jQuery is used in many popular websites. If a user has
already visited a web page that uses jQuery from a CDN, and then if he arrives at your
page then the jQuery file has already been cached by the browser, and no need to
download the file again.
4. DIFFERENT DOMAINS: There is a browser limit on concurrent connections (file
downloads) from a given domain. This number varies from browser to browser. For
example, a browser permits two active connections, so the third download is blocked
until one of the previous files has been fully retrieved. CDN files are hosted on a
different domain. In effect, a single CDN permits that browser to download a further
two files at the same time.
5. REDUCES SERVER LOAD: The HTTP request for jQuery is handled by the CDN
server, so the load o on your web server is reduced. This also means there is a saving
on your website bandwidth which in turn will reduce your hosting cost.
6. SEO FRIENDLY: Page load time is significant in SEO strategies because search
engines consider it as one of the factors. Thus, developers can use jQuery CDN to
ensure their webpage optimization for search engines.
Note: There are some limitations too. One of the disadvantages is that your client
firewall may block the CDN. So, you may have to request your client to white list the
CDN.
What if the jQuery files cannot be downloaded from the CDN?
Let us assume that the CDN is down or because of some network issue we are being
unable to download jQuery files from CDN. In that case we have to fallback to use jQuery
files that we have hosted in our own server. Let’s see how we can do that.
<script
src=”http://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js”></
script>
<script>
window.jQuery || document.write(‘<script src=”js/jquery-3.6.0.min.js”>\
x3C/script>’)
</script>
If jQuery is successfully downloaded then the jQuery property is added to the window
object. If this is not found then jQuery is not downloaded. In that case, we are referring
to the jQuery file that is present in our project folder.
jQuery ID Selector
What are selectors in jQuery?
Selectors are a very important concept of jQuery. Selectors are used for manipulating the
DOM elements. Following is the syntax to use Selector in jQuery.
Syntax: $(‘selector’).action(parameters);
Different Types of selectors available in jQuery:
There are many ways to select an element in jQuery such as
1. ID selector
2. Element Selector
3. Class selector
4. Attribute selector
5. Attribute value selector and many more
jQuery ID selector
To select any HTML element by its ID attribute value, we have to use the jQuery ID
selector. So, the jQuery #id selector selects the element with the specific id.
Syntax: $(‘#Id’)
Here, Id could be any value provided in the id attributes of the HTML element and you
should use # followed by its ID in the selector. For example, suppose we have a button
element in our HTML like below.
<button id=”btn1″>Click Me</button>
To select this button element, we have to use the jQuery id selector as follows
$(‘#btn1’)
The main advantage of using this jQuery ID selector is that we will get separate control
over each HTML element by its unique id and the manipulations will affect only that
HTML element. The usage of selecting the element by their ID name is exactly as same as
we have used in CSS. For example
$(‘#id1’): This will select any element with ID id1
$(‘div#id1’): This will select any div element which has the ID id1
$(‘#id1 #id2’): This will select any element having ID id2 which are a descendant of any
element having ID id1
$(‘#id1, #id2’): This will select any element having ID id1 or id2
Examples to understand jQuery ID Selector:
Now let’s jump to the practical to understand these things
<h1>jQuery ID Selector</h1>
<p>This is Some text</p>
<p id="p1">This is some another text</p>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('#p1').css('border', '2px solid blue');
});
});
</script>
Now in this example, we have the button element with id value “demo” and a paragraph
element with id value “p1”. We have to select the button and attach a click event handler
to it. By clicking the button, we have to add a border to the paragraph element having id
p1.
Notice that to select the button we have used $(‘#demo’) and to select the paragraph
we have used $(‘#p1’). Let’s see what will happen after clicking the button. When you
click on the Click Me button, you will get the following in the browser.

Notice that the border has been added to it.


Some important facts about jQuery ID Selector:
1. jQuery ID selector is the most efficient way to select a unique element in DOM. If you
know the id of an element you should always use the ID selector.
2. $(‘ID selector’) returns a jQuery object containing a collection of either zero or one
DOM element.
3. ID must be unique in the HTML. If you have two or more elements with the same id
then jQuery performs the action only to the first element.
Let’s understand the above points with an example:
<h1>jQuery ID Selector</h1>
<p id="p1">This is Some text</p>
<p id="p1">This is some another text</p>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('#p1').css('border', '2px solid blue');
});
});
</script>
With the above changes in place, run the code and click on the Click Me button, and you
should get the following in the browser.
Look that we have given the same id to both of the paragraph elements but the border is
applied to only the first element having that id.’
Difference between JavaScript document.getElementById() function and jQuery
ID selector
jQuery ID selector uses the document.getElementById() function of JavaScript. But $(‘ID
selector’) and document.getElementById() are not the same. Look at some differences of
these two:
1. JavaScript’s document.getElementById() will throw an error if the specified element is
not found. But $( ‘ID selector’ ) will not throw an error at all. jQuery will return only a
jQuery object with zero elements.
2. document.getElementById() returns a raw DOM element but jQuery ID selector
returns a jQuery object that wraps the DOM object and provides the jQuery methods
like css(),click() etc to it. To check the underlying DOM object from a jquery object
use $( ‘ID selector’ )[0].
3. document.getElementById() is faster than $( ‘ID selector’ ). If you don’t need the
additional functionalities of jQuery always go for the document.getElementById().
Example: To check if an element is returned by the jQuery id selector, use the
length property as shown in the below example.
<h1>jQuery ID Selector</h1>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
if ($('#demo').length > 0) {
alert('Element found')
}
else {
alert('Element not found')
}
});
</script>
Once you run the above code, the following alert will be popup in the browser.
Every HTML element can have its unique id attribute. Therefore, it is easy to get control
over the element by using the jQuery ID Selector. We can use this jQuery Id selector
whenever we want to access a specific element to perform some tasks.
jQuery Element Selector
jQuery Element Selector
To select any HTML element by its tag name, we have to use the jQuery Element
selector. To the jQuery function if we pass the element tag name as its selector then it is
called as jQuery Element selector. jQuery Element selector uses
document.getElementsByTagName() function of JavaScript.
Syntax: $(‘Element tag name’)
We can provide the element name that we want to select in the parenthesis. For example,
suppose that we have a button element in our HTML like below
<button>Click Me</button>
To select this button element, we have to use the element selector as follows
$(‘button’)
The usage of selecting the element by their tag name is exactly as same as we have used
in CSS. For example
$(‘p’): This will select all the paragraph tags
$(‘div button’): This will select all the <button> elements which are descendant of
<div> element
$(‘div, span, button’): This will select all the<div>, <span> and <button> elements
$(‘div > p’): This will select <p> elements that are a direct child of a <div> element
$(‘div ~ p’): This will select <p> elements appear after <div> element
$(‘p: first-child’): This will select only the first p element of its parent
$(‘p: last-child’): This will select only the last p element of its parent
$(‘p: nth-child(3)’): This will select only the 3rd p element of its parent
$(‘tr: odd’): This will select only the odd <tr> children of its parent
$(‘tr: even’): This will select only the even <tr> children of its parent
$(‘div: has(p)’): This will select all the div elements that have a p element
$(‘div: contains(“hello”)’): This will select all div elements that contains the string
hello
$(‘:header’): This will select all the header elements <h1>,<h2>,……….
$(‘:empty’): This will select all elements that are empty
$(‘:header:not(h1)’): This will select all header elements that are not h1
$(‘table:visible’): This will select all visible tables
$(‘ul li:eq(3)’): The fourth element in a list (index starts at 0)
$(‘ul li:gt(3)’): List elements with an index greater than 3
$(‘ul li:lt(3)’): List elements with an index less than 3
Example to understand jQuery Element Selector: Now let’s jump to the practical to
understand these things
<h1>jQuery Element Selector</h1>
<p>This is Some text</p>
<p>This is some another text</p>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('p').css('border', '2px solid blue');
});
});
</script>
Once you click on the Click Me button, the page changes as shown in the below image.
When we click on the button, we are selecting all the paragraph elements by $(‘p’) and
applying the border to all of them and hence you are getting the below output.

Example: Selecting descendant elements - In the below example we are targeting the
anchor tag which is the descendant of the DIV by $(‘div a’) and we apply the border on
the targeted element.
<h1>jQuery Element Selector</h1>
<div class="test">
<p>This is a DIV</p>
<a href="#">This is anchor element</a>
</div>
<br/>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('div a').css('border', '2px solid red');
});
});
</script>
When you click on the Click Me button, it will apply the border to the anchor element
which is descendent of the Div element as shown in the below image.

Example: Selecting multiple elements - In the below example, we are targeting all
the paragraph, span, anchor tags by $(‘p, span, a’) and apply the style to them.
<h1>jQuery Element Selector</h1>
<div class="test">
<p>This is some text</p>
<span>This is span element</span>
<br/><br/>
<a href="#">This is anchor element</a>
</div>
<br/>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('p, span, a').css('border', '2px solid red');
});
});
</script>
When you click on the Click Me button, it will apply the border to the paragraph, span,
and anchor elements as shown in the below image.
Example: In the below example, we are using a pseudo-selector. This will apply only to
the first paragraph tag.
<h1>jQuery Element Selector</h1>
<div class="test">
<p>This is 1st text</p>
<p>This is 2nd text</p>
<p>This is 3rd text</p>
</div>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#demo").click(function () {
$('p:first-child').css("border", "2px solid red");
});
});
</script>
When you click on the Click Me button, it will apply the border to the first paragraph
elements as shown in the below image.

Example: $(‘element’) returns a collection of elements, we can alert the number of


elements also by length method.
<h1>jQuery Element Selector</h1>
<div class="test">
<p>This is 1st text</p>
<p>This is 2nd text</p>
<p>This is 3rd text</p>
</div>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
alert($('p').length);
});
});
</script>
When you run the above code and click on the Click Me button, you will get the following
alert.

Example: In the below example we are selecting those odd table rows
<h1>jQuery Element Selector</h1>
<section id="sec">
<Table>
<tr>
<td>Front End</td>
<td>Back End</td>
</tr>
<tr>
<td>Bootstrap</td>
<td>NODE JS</td>
</tr>
<tr>
<td>jQuery</td>
<td>PHP</td>
</tr>
</Table>
</section>

<button id="demo">Click me</button>


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function(){
$("table tr:odd").css('backgroundColor','skyblue')
});

});
</script>
Now, run the above HTML code and click on the Click Me button, you will get the
following output.
Example: In the below example we are selecting those div elements which has a p
element.
<h1>jQuery Element Selector</h1>
<section id="sec">
<div>
<p>This is a Text</p>
</div>
<div>Demo text</div>
<div>Demo Text</div>
</section>

<button id="demo">Click me</button>


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function(){
$("div:has(p)").css('backgroundColor','skyblue')
});

});
</script>
Now, run the above HTML code and click on the Click Me button, you will get the
following output.

Example: In the below example, those div elements are only selected which contains the
string hello
<!DOCTYPE html>
<html>
<head>
<title>jQuery Element Selector</title>
</head>
<body>
<section id="sec">
<div>Hello World</div>
<div>Demo text</div>
<div> Hello Demo Text</div>
</section>
<button id="demo">Click me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function(){
$("div:contains('Hello')").css('backgroundColor','skyblue')
});
});
</script>
</body>
</html>
Now, run the above HTML code and click on the Click Me button, you will get the
following output.

Example: In the below example, we are selecting those headers inside the section
element which are not the <h4>
<section id="sec">
<div><h3>Hello World</h3></div>
<div><h4>Demo text</h4></div>
<div> Hello Demo Text</div>
</section>
<button id="demo">Click me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function(){
$
("section :header:not(h4)").css('backgroundColor','skyblue')
});
});
</script>
Now, run the above code and click on the Click Me button, you will get the following
output.
Example: In the below example, at first notice that only that <li> element of the list is
selected that is indexed at 3. Then notice that those <li> elements of the list are selected
that are indexed at less than 3.
<h3>jQuery Element Selector</h3>
<section id="sec">
<h5>JavaScript Libraries and Frameworks</h5>
<ul>
<li>jQuery</li>
<li>ReactJs</li>
<li>Angular</li>
<li>VueJS</li>
<li>NextJS</li>
</ul>
</section>
<button id="demo">Click me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('ul li:eq(3)').css('backgroundColor', 'skyblue');
$('ul li:lt(3)').css('backgroundColor', 'pink');
});
});
</script>
Now, run the above code and click on the Click Me button, you will get the following
output.
jQuery Class Selector
jQuery Class Selector
To select any HTML element by its class name, then we have to use the jQuery Class
selector. To the jQuery function if we pass the element class name as its selector then it
is called as jQuery Class selector. jQuery Class selector uses
document.getElementsByClassName() function of JavaScript.
Syntax: $(‘.clsass’)
For example, suppose that if we have button element in our HTML
<button class=”btn”>Click Me</button>
To select this button element, we have the selector as follows
$(‘.btn’)
The usage of selecting the element by their Class name is exactly as same as we have
used in CSS. For example
$(‘.a1’): This will select all the elements with class name a1
$(‘div.a1’): This will select all the div elements which have the class a1
$(‘.a1 .b1’): This will select all the elements having class b1 which are descendant of
any element having class a1
$(‘.a1,.b1’): This will select any element having class a1 or b1
$(‘.a1.b1’): This will select any element which have the both class a1 and b1
$(‘div > .p1’): This will select elements of class p1 that are a direct child of a <div>
element
$(‘.p1 ~ .p2’): This will select elements of class p2 appear after element of class p1
$(‘.p1: first-child’): This will select only the first element of class p1 of its parent
$(‘.p1: last-child’): This will select only the last element of class p1 of its parent
$(‘.p1: nth-child(3)’): This will select only the 3rd element of class p1 of its parent
$(‘.data: odd’): This will select only the odd children of element of class data
$(‘.data: even’): This will select only the even children of element of class data
$(‘.container: has(.p1)’): This will select all the elements having class container that
have a element of class p1
$(‘.container: contains(“hello”)’): This will select all elements having class container
that contains the string hello
$(‘.list:eq(3)’): The fourth element in a list having class list (index starts at 0)
$(‘.list:gt(3)’): Elements with class list with an index greater than 3
$(‘. list:lt(3)’): Elements with class list with an index less than 3
Note: The jQuery .class selector selects all elements with the specific class. Here, the
class refers to the class attribute of an HTML element. The class attribute is used to set a
particular style for several HTML elements.
Example1: $( ‘Class selector’ ) returns a collection of elements, we can alert the number
of elements also by length method.
<h1>jQuery Class Selector</h1>
<div class="test">
<p class="p1">This is 1st text having class p1</p>
<p class="p1">This is 2nd text having class p1</p>
<p>This is 3rd text</p>
</div>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
alert($('.p1').length);
});
});
</script>
Once you click on the Click Me button, it will give you the following alert.

Example2: In the below example we are selecting all the elements which have the class
p1 by $( ‘.p1’ ) and applying the border.
<h1>jQuery Class Selector</h1>
<p class="p1">This is 1st text</p>
<p class="p1">This is 2nd text</p>
<p>This is 3rd text</p>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('.p1').css('border','2px solid red');
});
});
</script>
Run the above code and then click on the Click Me button and you should get the
following output.
Example3: In the below example we are selecting those div elements which have the
class p1 by $( ‘div.p1’ ). Notice that p elements have also class p1 but they are not
targeted at all.
<h1>jQuery Class Selector</h1>
<div class="p1">
<p class="p1">This is 1st text</p>
<p class="p1">This is 2nd text</p>
</div>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('div.p1').css('border','2px solid red');
});
});
</script>
Run the above code and then click on the Click Me button and you should get the
following output.

Example4: In the below example, notice that only those elements of class p1 are
targeted which are descendants of the class test. The element of class p1 is not targeted
which is outside that div of the class test.
<h1>jQuery Class Selector</h1>
<div class="test">
<p class="p1">This is 1st text</p>
<p class="p1">This is 2nd text</p>
</div>
<p class="p1">This is 3rd text</p>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('.test .p1').css('border','2px solid red');
});
});
</script>
Run the above HTML code and then click on the Click Me button and you should get the
following output.

Example5: In the below example, we are selecting those elements which have the class
either test or p1. Notice that borders have been applied to those elements having one of
the class test or p1.
<h1>jQuery Class Selector</h1>
<div class="test">
<p class="p1">This is 1st text</p>
<p class="p1">This is 2nd text</p>
<p>This is 3rd text</p>
</div>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('.test, .p1').css('border','2px solid red');
});
});
</script>
Run the above HTML code and then click on the Click Me button and you should get the
following output.
Example6: In the below example only, we are selecting those elements which have both
the class test and p1.
<h1>jQuery Class Selector</h1>
<div class="test p1">
<p class="p1">This is 1st text</p>
<p class="p1">This is 2nd text</p>
<p>This is 3rd text</p>
</div>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('.test.p1').css('border','2px solid red');
});
});
</script>
Run the above code and then click on the Click Me button and you should get the
following output.

Example7: In the below example, we are selecting the children of list ‘class’ which is
indexed at 3, and those who are indexed at less than 3.
<h1>jQuery Element Selector</h1>
<section id="sec">
<h6>Front End Technologies</h6>
<ul>
<li class="list">jQuery</li>
<li class="list">ReactJs</li>
<li class="list">Angular</li>
<li class="list">Bootstrap</li>
<li>Foundation UI</li>
</ul>
</section>
<button id="demo">Click me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('ul li:eq(3)').css('backgroundColor', 'skyblue');
$('.list:lt(3)').css('backgroundColor', 'pink');
});
});
</script>
Run the above code and then click on the Click Me button and you should get the
following output.

Example8: In the below example we are selecting those <li> elements which are not
having a class ‘list’. As a result, you can see the last child is selected.
<h1>jQuery Element Selector</h1>
<section id="sec">
<h6>Front End Technologies</h6>
<ul>
<li class="list">jQuery</li>
<li class="list">ReactJs</li>
<li class="list">Angular</li>
<li class="list">Bootstrap</li>
<li>Foundation UI</li>
</ul>
</section>
<button id="demo">Click me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('ul li:not(.list)').css('backgroundColor', 'skyblue');

});
});
</script>
Run the above HTML and then click on the Click Me button and you should get the
following output.

Example9: In the below example, we are selecting the element having class ‘container’
which has the element of class ‘p1’.
<h1>jQuery Element Selector</h1>
<section id="sec">
<div class="container">
<p class="p1">Demo text</p>
</div>
<div><p>Demo text 2 </p></div>
</section>
<button id="demo">Click me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('.container:has(.p1)').css('backgroundColor', 'skyblue');

});
});
</script>
Run the above HTML and then click on the Click Me button and you should get the
following output.
Example10: In the below example, we are selecting those elements having class ‘p1’ and
that contains the string “Demo”
<h1>jQuery Element Selector</h1>
<section id="sec">
<p class="p1">Demo text</p>
<p class="p1">Dummy text</p>
<p class="p1">Demo text</p>
</section>
<button id="demo">Click me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('.p1:contains("Demo")').css('backgroundColor' , 'skyblue')
;
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.

jQuery Attribute Selector


jQuery Attribute Selector
If we want to select any HTML element by its attribute name, then we have to use the
jQuery Attribute selector. To the jQuery function if we pass the attribute name as its
selector then it is called as jQuery Attribute selector.
Syntax: $(‘[attribute]’)
For example, suppose that we have an input element in our HTML
<input name=’fname’>
To select this input element, we have to use the attribute selector as follows
$(‘input[name]’)
The usage of selecting the element by their Attributes name is exactly as same as we
have used in CSS. For example
1. $(‘[name]’): This will select all the elements with the attribute name
2. $(‘input[name]’): This will select all the input elements which have the attribute
name
3. $(‘[name=”a1″]’): This will select all the elements having attribute name with value
a1
4. $(‘input[name=”a1″]’): This will select all the input elements having attribute name
with value a1
Points to Remember while working with jQuery Attribute Selector:
The CSS specification allows elements to be identified by their attributes. While not
supported by some older browsers for the purpose of styling documents, jQuery allows
you to employ them regardless of the browser being used.
When using any of the following attribute selectors, you should account for attributes
that have multiple, space-separated values. Since these selectors see attribute values as a
single string, this selector, for example, $(“a[rel=’nofollow’]”), will select <a
href=”example.html” rel=”nofollow”>Some text</a> but not <a href=”example.html”
rel=”nofollow foe”>Some text</a>.
Attribute values in selector expressions must follow the rules for W3C CSS selectors; in
general, that means anything other than a valid identifier should be surrounded by
quotation marks.
1. double quotes inside single quotes: $(‘a[rel=”nofollow self”]’)
2. single quotes inside double quotes: $(“a[rel=’nofollow self’]”)
3. escaped single quotes inside single quotes: $(‘a[rel=\’nofollow self\’]’)
4. escaped double quotes inside double quotes: $(“a[rel=\”nofollow self\”]”)
Example: In the below example, we are targeting those elements which have the name
attribute by $(‘[name]’) and applying the border around them.
<h3>jQuery Attribute Selector</h3>
<div>
<form action="">
<input type="text" name="fname" placeholder="Enter your fist
name"> <br /><br />
<input type="text" name="lname" placeholder="Enter your last
name"><br /><br />
<input type="password" placeholder="Enter the password"><br />
</form>
</div>
<button id="demo">Submit</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('[name]').css("border", "2px solid black");
});
</script>
Now, run the above HTML code and you will see that the border is applied to the First
and Last Name text boxes as shown in the below image.

Example: In the below example, we are using the same HTML and we are targeting
those input elements which have the attribute type by $(‘input[type]’)
<h3>jQuery Atrribute Selector</h3>
<div>
<form action="">
<input type="text" name="fname" placeholder="Enter Your first
name"> <br/><br/>
<input type="text" name="lname" placeholder="Enter Your last name">
<br/><br/>
<input type="password" placeholder="Enter the password"> <br/><br/>
</form>
</div>

<button id="demo">Submit</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('input[type]').css('border','2px solid black');
});
</script>
Now, run the above HTML code and you will see that the border is applied to all the text
boxes as shown in the below image.
Example: In the below example, we are targeting those input elements have the
attribute required
<h3>jQuery Atrribute Selector</h3>
<div class="test">
<form action="">
<input type="text" name="fname" placeholder="Enter Your first name"
required> </br></br>
<input type="text" name="lname" placeholder="Enter Your last name"
></br></br>
<input type="password" name="password" placeholder="Enter the
password" required> </br></br>
</form>
</div>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('[required]').css('border','2px solid red');
});
</script>
Now, run the above HTML code and you should get the following output.

Example: In the below example, only the div element which has the title attribute is
selected. span element has also the title attribute but that is not selected
<h3>jQuery Attribute Selector</h3>
<section>
<div title="div">This is DIV element with title</div>
<span title="span">This is span element with title</span>
<p>This is p Element</p>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('div[title]').css('backgroundColor', 'skyblue');
});
</script>
Now, run the above HTML code and you will get the following output.

Example: In the below example, we are targeting that element(s) having the name
attribute with value fname by $( ‘[name=”fname”]’ ). Notice that other elements with
name attribute which don’t have the value fname those are not targeted.
<h3>jQuery Atrribute Selector</h3>
<div class="test">
<form action="">
<input type="text" name="fname" placeholder="Enter Your first
name"> </br></br>
<input type="text" name="lname" placeholder="Enter Your last
name"></br></br>
<input type="password" name="password" placeholder="Enter the
password"></br></br>
</form>
</div>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('[name="fname"]').css('border','2px solid red');
});
});
</script>
Now, run the above HTML code and click on the Click Me button, you will get the
following output.

Example: In the below example, we are targeting those input elements which have the
type attribute with value text by $(‘input[type=”text”]’). Notice that, that element with
the type attribute with value password is not targeted here.
<h3>jQuery Attribute Selector</h3>
<div class="test">
<form action="">
<input type="text" name="fname" placeholder="Enter Your first
name"> </br></br>
<input type="text" name="lname" placeholder="Enter Your last
name"></br></br>
<input type="password" name="password" placeholder="Enter the
password"> </br></br>
</form>
</div>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('input[type="text"]').css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.
Example: In the below example, we are targeting those input elements whose type
attribute value is text and who are children of div element whose title attribute value is
main.
<h3>jQuery Atrribute Selector</h3>
<div class="test">
<form action="">
<div title="main">
<input type="text" name="fname" placeholder="Enter Your first name">
</br></br>
<input type="text" name="lname" placeholder="Enter Your last
name"></br></br>
</div>
<input type="password" name="password" placeholder="Enter the
password"></br></br>
</form>
</div>

<button class="demo">Click Me</button>


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('div[title="main"] input[type="text"]').css('border', '2px solid
red');
});
});
</script>
Now, run the above HTML Code and then click on the Click Me button and you should
get the following output.
jQuery Attribute Value Selector
jQuery Attribute Value Selectors
Following are the lists of jQuery Attribute Value Selectors.
Attribute Equals Selector:
Syntax: [name = “value”]
Example: $(‘[title=”sample1Title”]’)
Selects all the elements that have title attribute value equal to sample1Title.
Attribute Not Equal Selector:
Syntax: [name != “value”]
Example: $(‘[title !=”sample1Title”]’)
Selects all the elements that have title attribute value not equal to sample1Title.
Attribute Contains Selector:
Syntax: [name *= “value”]
Example: $(‘[title *=”Title”]’)
Selects all the elements that have title attribute value containing given substring ‘Title’.
Attribute Contains Word Selector:
Syntax: [name ~= “value”]
Example: $(‘[title ~=”mySample”]’)
Selects all the elements that have title attribute value containing the given word –
mySample, delimited by space
Attribute Contains Prefix Selector:
Syntax: [name |= “value”]
Example: $(‘[title |=”mySample”]’)
Selects all the elements that have title attribute value mySample or starting with
mySample followed by hyphen(-).
Attribute Starts with Selector:
Syntax: [name ^= “value”]
Example: $(‘[title ^=”div”]’)
Selects all the elements that have title attribute value starting with div
Attribute Ends with Selector:
Syntax: [name $= “value”]
Example: $(‘[title $=”Heading”]’)
Selects all the elements that have title attribute value ending with Heading.
Let us jump to the practical session to understand these selectors.
Example: Attribute Equals Selector: [name = “value”]
In the below example, we are selecting all the elements that have title attribute value
equal to sample1Title and applying the border by clicking the button
<h3>jQuery Atrribute Value Selector</h3>
<section class="test">
<p title="sample1Title">This is a paragraph</p>
<span title="sample1Title">This is a Span </span>
<div title="sample">This is a DIV</div>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('[title="sample1Title"]').css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.

Example: Attribute Not Equal Selector: [name != “value”]


In the below example, we are selecting all the elements inside the section that have title
attribute value not equal to sample1Title and applying the border by clicking the button.
Notice that only the div element is matching the criteria.
<h3>jQuery Atrribute Value Selector</h3>
<section>
<p title="sample1Title">This is a paragraph</p>
<span title="sample1Title">This is a Span </span>
<div title="sample">This is a DIV</div>
</section>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$( 'section [title !="sample1Title"]').css('border','2px
solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.

Example: Attribute Contains Selector: [name *= “value”]


In the below example, we are selecting all the elements that have title attribute value
containing the given substring ‘Title’ and applying those to the border. Notice that,
Paragraph and span tag is matching the criteria.
<h3>jQuery Atrribute Value Selector</h3>
<section>
<p title="sample1Title">This is a paragraph</p>
<span title="sample1Title">This is a Span </span>
<div title="sample">This is a DIV</div>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('[title *= "Title"]').css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.
Example: Attribute Contains Word Selector: [name ~= “value”]
In the below example, we are selecting all the elements that have title attribute value
containing the given word – mySample, delimited by space. Notice that the p element has
also an attribute value containing the word mySample but that is not delimited by space.
So that is not selected here.
<h3>jQuery Atrribute Value Selector</h3>
<section>
<p title="mySampleTitle">This is a paragraph</p>
<span title="Title mySample">This is a Span </span>
<div title="mySample Title">This is a DIV</div>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$( '[title ~= "mySample"]' ).css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.

Example: Attribute Contains Prefix Selector: [name |= “value”]


In the below example, we are selecting all the elements that have title attribute value
mySample or starting with mySample followed by hyphen(-). Notice that, div is also
having mySample but that isn’t followed by hyphen(-). So that is not selected here.
<h3>jQuery Atrribute Value Selector</h3>
<section>
<p title="mySample-Title">This is a paragraph</p>
<span title="mySample">This is a Span </span>
<div title="mySample Title">This is a DIV</div>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$( '[title |= "mySample"]' ).css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.

Example: Attribute Starts with Selector: [name ^= “value”]


In the below example, we are selecting all the elements that have title attribute value
starting with div and applying the border. Notice that div has also ‘div’ in the title
attribute value but it is not started with that.
<h3>jQuery Atrribute Value Selector</h3>
<section>
<p title="divmySample-Title">This is a paragraph</p>
<span title="divmySample">This is a Span </span>
<div title="mySamplediv Title">This is a DIV</div>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$( '[title ^= "div"]' ).css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.

Example: Attribute Ends with Selector: [name $= “value”]


In the below example, we are selecting all the elements that have title attribute value
ending with Heading.
<h3>jQuery Atrribute Value Selector</h3>
<section>
<p title="mySampleHeading">This is a paragraph</p>
<span title="mySample">This is a Span </span>
<div title="mySamplediv Heading">This is a DIV</div>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$( '[title $= "Heading"]' ).css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.

jQuery Case Insensitive Attribute Value Selector


jQuery Case Insensitive Attribute Value Selector
jQuery attribute value selectors are generally case-sensitive. But we have certain steps to
follow to make these attribute value selectors case-insensitive. Let us see how to do this
by practical example.
Example: In the below example, notice that all the div elements have the title attribute
value mysample but the casing is different. In our jQuery code, our selector is matching
with only the 1st div element so that is only targeted here.
<h3>jQuery Case Insensitive Attribute Value Selector</h3>
<section>
<div title="MySample">This is text one</div>
<div title="MYSAMPLE">This is text two</div>
<div title="mysample">This is text three</div>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$( 'div[title = "MySample"]' ).css('border','2px solid
red');
});
});
</script>
Run the above HTML code, then click on the Click Me button and you should get the
following output.

How to make the jQuery attribute value selector case-insensitive?


Now let’s see how to make the jQuery attribute value selector case-insensitive. We are
going to change the previous example to make the jQuery attribute value selector case-
insensitive. In the below example, $(‘div[title]’) will return a collection of all div elements
having the attribute title. Now from that collection, we have to find out those div
elements which have the title attribute value ‘mysample’ irrespective of the case. We are
now using the filter method and for each div element in that collection, we are retrieving
the attribute value, converting them to lower case using the toLowerCase built-in
method, and comparing them to ‘mysample’. Now this will work as case insensitive.
<h3>jQuery Case Insensitive Attribute Value Selector</h3>
<section>
<div title="MySample">This is text one</div> <br />
<div title="MYSAMPLE">This is text two</div> <br />
<div title="mysample">This is text three</div> <br />
</section>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$('div[title]').filter(function () {
return $(this).attr('title').toLowerCase() ==
"mysample";
}).css('border', '2px solid red');
});
});
</script>
Run the above HTML Code, then click on the Click Me button and you should get the
following output as expected.

Example: jQuery attribute contains selector - In the below example, notice that all
the div elements have the title attribute value containing substring ‘div’ but the casing is
different. In our jQuery code, our selector is matching with only the 1st div element so
that is only targeted here.
<h3>jQuery Case Insensitive Attribute Value Selector</h3>
<section>
<div title="DivSample">This is text one</div> </br>
<div title="DIVSample">This is text two</div> </br>
<div title="divSample">This is text three</div> </br>
</section>

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


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$( 'div[title *="Div"]' ).css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.
How to make the jQuery attribute contains selector case-insensitive?
Now let’s see how to make the jQuery attribute contains selector case-insensitive. Please
have a look at the below example. Here, $(‘div[title]’) will return a collection of all div
elements having the attribute title. Now from that collection we have to find out those div
elements which have title attribute value containing the substring ‘div’ irrespective of the
case. For that, we are using RegEx of JavaScript (Our RegEx is /Div/i. For case-
insensitivity we are using this ‘i’ flag). Now for each div element in that collection, we are
retrieving the attribute value and comparing it with the RegEx. Now this will work as
case-insensitive.
<h3>jQuery Case Insensitive Attribute Value Selector</h3>
<section>
<div title="DivSample">This is text one</div> </br>
<div title="DIVSample">This is text two</div> </br>
<div title="divSample">This is text three</div> </br>
</section>
<button id="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function () {
$( 'div[title]' ).filter(function () {
return (/Div/i).test($(this).attr('title'));
})
.css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output.
Example: Now, this thing can be achieved in a much simpler way. In the below example
we are using the I flag to the title attribute value in the selector so that the search
becomes case insensitive. Notice that all the div elements are targeted irrespective of the
case
<h3>jQuery Atrribute Value Case Insensitive Selector</h3>
<section>
<div title="MySample">This is text one</div> </br>
<div title="MYSAMPLE">This is text two</div> </br>
<div title="mysample">This is text three</div> </br>
</section>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('div[title ="MySample" i]').css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output as expected.

Example: Now we will see the case of the attribute contains selector. In the below
example, we are using the I flag to the title attribute value in the selector so that the
search becomes case insensitive. Notice that all the div elements are targeted
irrespective of the case.
<h3>jQuery Atrribute Value Case Insensitive Selector</h3>
<section>
<div title="DivSample">This is text one</div> </br>
<div title="DIVSample">This is text two</div> </br>
<div title="divSample">This is text three</div> </br>
</section>

<button class="demo">Click Me</button>


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$( 'div[title *="Div" i]' ).css('border','2px solid red');
});
});
</script>
Run the above HTML Code and then click on the Click Me button and you should get the
following output as expected.

jQuery $(‘input’) vs $(‘:input’) Selectors


jQuery $(‘input’) Selector: This selector is a jQuery Element Selector. This selector
targets all the <input> tags. But in our form generally there are more useful tags other
than input tags such as <select>, <button>, <textarea> etc. $(‘input’) will not target
these tags.
jQuery $(‘:input’) Selector: This selector in jQuery targets all the input fields in our
document including <select>, <button>, <textarea>
Example: Understand the use of jQuery $(‘input’) vs $(‘:input’) Selectors
Let us see understand how these two selectors work with an example.
We are making a simple form in HTML. In the below example, notice carefully that when
we are using the selector as $(‘input’) then we are getting only those input tags (excluded
textarea, select, and button). But when we are targeting all input fields by $(‘:input’).
Then all input fields are targeted here.
<section>
<form action="/">
<label for="name">Name: </label>
<input type="text" name="Name" />

<label for="email">Email: </label>


<input type="email" name="Email" /> </br> </br>

<fieldset>
<legend>Skillset: </legend>
<label>HTML:
<input type="checkbox" value="HTML"
name="checkgroup[]" /></label>
<label>CSS:
<input type="checkbox" value="CSS"
name="checkgroup[]" /></label>
<label>JavaScript:
<input type="checkbox" value="JavaScript"
name="checkgroup[]" /></label>
<label>jquery:
<input type="checkbox" value="jquery"
name="checkgroup[]" /></label>
</fieldset> </br>

<label>Enter your DOB</label>


<input type="datetime-local" name="datetime" /> </br>

<label>Upload your Photo: </label>


<input type="file" name="file" /> </br>

<label>Years of experience: </label>


<input type="number" name="number" /> </br>

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

<fieldset>
<legend>Male</legend>
<label>Male:
<input type="radio" value="Male" name="radiogroup"
/></label>
<label>Female:
<input type="radio" value="Female" name="radiogroup"
/></label>
</fieldset> </br>

<label>Enter your contact number </label>


<input type="tel" name="tel" /> </br>

<label>Enter your website </label>


<input type="url" name="url" /> </br>

<label>Select the position</label>


<select name="select2" size="3" multiple>
<option>Web developer</option>
<option>Web Designer</option>
</select> </br> </br>
<fieldset>
<legend>Enter your university </legend>
<input type="text" name="datalist" list="samplelist">
<datalist id="samplelist">
<option>MAKAUT</option>
<option>Techno India</option>
<option>If other please specify</option>
</datalist>
</fieldset> </br>
<label>Any other comments</label>
<textarea name="textarea"></textarea>
</form>
</section>
<button id="demo">Submit</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
const allInput = $('input').length;
const allInputSelector = $(':input').length;
console.log(`Total number of <input> tags are ${allInput} and
total number of <:inputs> are ${allInputSelector}` );
console.log($('input'));
console.log($(':input'));
});
</script>
Now open the browser developers’ tool by pressing the F12 key and have a look at the
console tab as shown in the below image.

In the first console.log, we are printing the number of elements targeted by $(‘input’) and
$(‘:input’) respectively. Notice that <input> tags are 15 in number but there is a total of
18 input fields in our form. The other three are select, textarea, and button.
In the second console.log, we are printing the whole jQuery object returned by $(‘input’)
and $(‘:input’) respectively. You can see the difference clearly. In the object returned by
$(‘:input’) we are getting three extra elements select, textarea and button.
Which one is better for performance $(‘input[type=”text”]’) or $
(‘:input[type=”text”]’)?
$(‘input[type=”text”]’) is better for performance over $(‘:input[type=”text”]’). This is
because
$(‘:input[type=”text”]’) needs to scan all input elements including textarea, select,
button, etc. whereas
$(‘input[type=”text”]’) scans only input elements.
So if you want to find elements with an input tag, it is always better to use $
(‘input[type=”text”]’) over
$(‘:input[type=”text”]’).
jQuery Checked Selector
jQuery checked selector
The jQuery checked selector selects all the radio and checkbox input elements that are
checked. This is used to get the value of the radio or checkbox which the user has
selected.
Syntax:
$(‘input[type=”radio”]:checked’): This will select all the radio input elements which
are checked
$(‘input[type=”checkbox”]:checked’): This will select all the checkbox input elements
which are checked
Example: jQuery Checked Selector with Radio button - We are creating basic radio
input elements. In the below example, we first have found the length of the collection
returned by $(‘input[type=”radio”]:checked’). Notice that the length of the collection is 1
because we have checked one radio button.
<section>
<form action="/">
<fieldset>
<legend>Male</legend>
<label>Male:
<input type="radio" name="radiogroup" value="Male"
/></label>
<label>Female:
<input type="radio" name="radiogroup"
value="Female"/></label>
</fieldset>
</form>
</section>
</br>
<button id="demo" value="submit">Submit</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function(){
const RadioChecked= $('input[type="radio"]:checked').length;
console.log(`Total ${RadioChecked} radio buttons are
checked`);
});
});
</script>
Run the above HTML Code and then select one radio button and click on the Submit
button as shown in the below image.
Now, open the browser developer’s tool by pressing the F12 key and then select the
console tab and you should see the following log.

Example: jQuery Checked Selector with Check boxes - In the below example, we
first have found the length of the collection returned by $
(‘input[type=”checkbox”]:checked’).
<section>
<form action="/">
<fieldset>
<legend>Skillset: </legend>
<label>HTML:
<input type="checkbox" name="checkgroup[]"
value="HTML" /></label>
<label>CSS:
<input type="checkbox" name="checkgroup[]"
value="CSS"/></label>
<label>JavaScript:
<input type="checkbox" name="checkgroup[]"
value="JavaScript"/></label>
<label>jquery:
<input type="checkbox" name="checkgroup[]"
value="jquery"/></label>
</fieldset>
</form>
</section> </br>

<button id="demo" value="submit">Submit</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function(){
const CheckboxChecked= $
('input[type="checkbox"]:checked').length;
console.log(`Total ${CheckboxChecked} checkboxes are
checked`);
});
});
</script>
Run the above HTML Code and then select two checkboxes and click on the Submit
button as shown in the below image.
Now, open the browser developer’s tool by pressing the F12 key and then select the
console tab and you should see the following log. Notice that the length of the collection
is 2 because we have checked two checkboxes.

Example: In the below example, we will try to get the value of the radio or checkboxes
which the user has checked. Here we are applying each method to the checked radio
buttons and printing the value on the console.
<section>
<form action="/">
<fieldset>
<legend>Male</legend>
<label>Male:
<input type="radio" name="radiogroup" value="Male"
/></label>
<label>Female:
<input type="radio" name="radiogroup"
value="Female"/></label>
</fieldset>
</form>
</section> </br>

<button id="demo" value="submit">Submit</button>


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function(){
$('input[type="radio"]:checked').each(function(){
console.log($(this).val());
})
});
});
</script>
Run the above HTML Code and then select the Female radio button and click on the
Submit button as shown in the below image.
Now, open the browser developer’s tool by pressing the F12 key and then select the
console tab and you should see the following log. Notice that, we have checked the Male
radio button and that is displayed on the console.

Example: In the below example, we are applying each method to the checked checkbox
buttons and printing the value on the console.
<section>
<form action="/">
<fieldset>
<legend>Skillset: </legend>
<label>HTML:
<input type="checkbox" name="checkgroup[]"
value="HTML" /></label>
<label>CSS:
<input type="checkbox" name="checkgroup[]"
value="CSS"/></label>
<label>JavaScript:
<input type="checkbox" name="checkgroup[]"
value="JavaScript"/></label>
<label>jquery:
<input type="checkbox" name="checkgroup[]"
value="jquery"/></label>
</fieldset>
</form>
</section>
</br>
<button id="demo" value="submit">Submit</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#demo').click(function(){
$('input[type="checkbox"]:checked').each(function(){
console.log($(this).val());
})
});

});
</script>
Run the above HTML Code and then select the HTML and CSS checkboxes and click on
the Submit button as shown in the below image.

Now, open the browser developer’s tool by pressing the F12 key and then select the
console tab and you should see the following log. Notice that, we have checked HTML
and CSS & checkboxes and that is displayed on the console.

Example: Now let’s see an example in which both radio and checkbox elements are
present. In the below example, we have two buttons ‘Get radio value’, ‘Get checkbox
value’. If we click on the 1st button, we will see only the radio buttons which we have
selected. And the same with the checkbox button
<section>
<form action="/">
<fieldset>
<legend>Male</legend>
<label>Male:
<input type="radio" name="radiogroup" value="Male"
/></label>
<label>Female:
<input type="radio" name="radiogroup" value="Female"
/></label>
</fieldset>

<fieldset>
<legend>Skillset: </legend>
<label>HTML:
<input type="checkbox" name="checkgroup[]"
value="HTML" /></label>
<label>CSS:
<input type="checkbox" name="checkgroup[]"
value="CSS" /></label>
<label>JavaScript:
<input type="checkbox" name="checkgroup[]"
value="JavaScript" /></label>
<label>jquery:
<input type="checkbox" name="checkgroup[]"
value="jquery" /></label>
</fieldset>
</form>
</section>
</br>
<button class="demo" id="radio" value="submit">Get radio value</button>
<button class="demo" id="checkbox" value="submit">Get checkbox
value</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#checkbox').click(function () {
let options = [];
$('input[type="checkbox"]:checked').each(function () {
options.push($(this).val());
})
alert(`You have selected the options ${options.join(", ")}`)
});
$('#radio').click(function () {
$('input[type="radio"]:checked').each(function () {
alert(`You have selected ${$(this).val()}`);
})
});
});
</script>
Now, run the above HTML code and check yourself.
Select Values of Checkbox Group with jQuery
How to select values of checkbox group with jQuery? In our previous article, we
have learned that how to get the values of selected checkboxes. But there is a small
issue. Let us have a look at the issue first and for this please have a look at the following
example.
<section>
<form action="/">
<fieldset>
<legend>Skillset: </legend>
<label>HTML:
<input type="checkbox" name="skillset" value="HTML"
/></label>
<label>CSS:
<input type="checkbox" name="skillset"
value="CSS"/></label>
<label>JavaScript:
<input type="checkbox" name="skillset"
value="JavaScript"/></label>
<label>jquery:
<input type="checkbox" name="skillset"
value="jquery"/></label>
</fieldset>
<br>
<fieldset>
<legend>Preferred Interview Location </legend>
<label>Kolkata:
<input type="checkbox" name="location"
value="Kolkata" /></label>
<label>Bhubaneshwar:
<input type="checkbox" name="location"
value="Bhubaneshwar"/></label>
<label>Bangalore:
<input type="checkbox" name="location"
value="Bangalore"/></label>
<label>Pune:
<input type="checkbox" name="location"
value="Pune"/></label>
</fieldset>
</form>
</section> </br>
<button class="demo" id="skillset" value="submit">Get skillset</button>
<button class="demo" id="location" value="submit">Get location</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#skillset').click(function () {
var valueStore = [];
$.each($("input[type='checkbox']:checked"), function () {
valueStore.push($(this).val());
});
alert("My favourites are: " + valueStore.join(", "));
});

$('#location').click(function () {
var valueStore = [];
$.each($("input[type='checkbox']:checked"), function () {
valueStore.push($(this).val());
});
alert("My favourites are: " + valueStore.join(", "));
});
});
</script>
Once you run the above HTML code, you will get the following output. As you can see in
the below image, here, we have two groups of checkboxes.
What our requirement is, when we click on the corresponding button, then we should get
the corresponding checked value of the checkbox groups. But if we apply the event
handler on both the buttons as we have done in our previous example, then we are
getting the result as follows whether we click on the Get Skillset and Get Location
button.
But we don’t want that. We want that if we click on the ‘Get skillset’ button then only we
should get the values of the Skillset group and the same with the Location group. Now
let’s see how to achieve that functionality?
Approach1: We are facing that problem because we are using the type attribute to the
input element. So, they are targeting all checkboxes. But what if we use the name
attribute. The name attribute is different for the different groups of checkboxes. That will
solve our problem. So, modify the script section of the previous example as follows.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#skillset').click(function () {
var valueStore = [];
$.each($("input[name='skillset']:checked"), function () {
valueStore.push($(this).val());
});
alert("My favourite skillset are: " + valueStore.join(", "));
});
$('#location').click(function () {
var valueStore = [];
$.each($("input[name='location']:checked"), function () {
valueStore.push($(this).val());
});
alert("My favourites location are: " + valueStore.join(", "));
});
});
</script>
In the above code, By $(‘input[name=”skillset”]:checked’) we are targeting that
group of checkbox named skillset. And the same we are doing with the group of checkbox
named location by $(‘input[name=”location”]:checked’). With the above script
section in place, now click on the Get Skillset button, you will only get Skill Set checked
check box values as shown in the below image.

Then click on the Get location button, you will get only the location-selected checkboxes
values as shown in the below image.
Our desired functionality is done.
Approach2: But there is another problem with the first approach. We are creating
different handlers for different buttons. What if there are many checkbox groups in our
form? Will we create a different handler to get the values of every checkbox group?
No instead of this we can create a function and pass a parameter to that function. That
parameter will dynamically change the value of the name attribute and we will invoke
that function by just using two different parameters. To do so, please modify the script
section of your code as follows.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function() {
$('#skillset').click(function() {
getCheckedValues('skillset');
});
$('#location').click(function() {
getCheckedValues('location');
});
});

function getCheckedValues(nameAttr) {
var valueStore = [];
$.each($("input[name='" + nameAttr + "']:checked"), function() {
valueStore.push($(this).val());
});
alert("My favourites " + nameAttr + " are: " + valueStore.join(", "));
}
</script>
With the above changes in place, now click on the Get Skillset button, you will only get
selected Skill Set check box values as shown in the below image.

Then click on the Get location button, you will get only the selected location check box
values as shown in the below image.
Thus, our functionality is achieved with a minimal piece of code. Following is the
complete code of the above example.
<section>
<form action="/">
<fieldset>
<legend>Skillset: </legend>
<label>HTML:
<input type="checkbox" name="skillset" value="HTML"
/></label>
<label>CSS:
<input type="checkbox" name="skillset"
value="CSS"/></label>
<label>JavaScript:
<input type="checkbox" name="skillset"
value="JavaScript"/></label>
<label>jquery:
<input type="checkbox" name="skillset"
value="jquery"/></label>
</fieldset>
<br>
<fieldset>
<legend>Preferred Interview Location </legend>
<label>Kolkata:
<input type="checkbox" name="location"
value="Kolkata" /></label>
<label>Bhubaneshwar:
<input type="checkbox" name="location"
value="Bhubaneshwar"/></label>
<label>Bangalore:
<input type="checkbox" name="location"
value="Bangalore"/></label>
<label>Pune:
<input type="checkbox" name="location"
value="Pune"/></label>
</fieldset>
</form>
</section> </br>
<button class="demo" id="skillset" value="submit">Get skillset</button>
<button class="demo" id="location" value="submit">Get location</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function() {
$('#skillset').click(function() {
getCheckedValues('skillset');
});
$('#location').click(function() {
getCheckedValues('location');
});
});

function getCheckedValues(nameAttr) {
var valueStore = [];
$.each($("input[name='" + nameAttr + "']:checked"), function() {
valueStore.push($(this).val());
});
alert("My favourites " + nameAttr + " are: " + valueStore.join(",
"));
}
</script>
How to get Selected Checkbox Text in jQuery
How to Get Selected Checkbox Text in jQuery? In the previous article, we have
learned to extract the values of different checkbox groups. In the examples of the
previous article notice one thing, our value of the checkbox and the label text was the
same. But what if they were different? How to extract the checkbox label texts? In this
article, we will discuss that with Examples.
Example: Let’s quickly build the HTML.
<section>
<form action="/">
<fieldset>
<legend>Skillset: </legend>
<label for="HTML">HTML5</label>
<input type="checkbox" name="skillset" value="HTML" />
<label for="CSS">CSS3</label>
<input type="checkbox" name="skillset" value="CSS" />
<label for="JavaScript">JS</label>
<input type="checkbox" name="skillset" value="JavaScript" />
<label for="jquery">jquery3.6</label>
<input type="checkbox" name="skillset" value="jquery" />
</fieldset>
<br>
<fieldset>
<legend>Preferred Interview Location </legend>
<label for="Kolkata">KOL</label>
<input type="checkbox" name="location" value="Kolkata" />
<label for="Bhubaneshwar">BBS</label>
<input type="checkbox" name="location"
value="Bhubaneshwar" />
<label for="Bangalore">BLR</label>
<input type="checkbox" name="location" value="Bangalore" />
<label for="Pune">PUN</label>
<input type="checkbox" name="location" value="Pune" />
</fieldset>
</form>
</section>
</br>
<button class="demo" id="skillset" value="submit">Get skillset</button>
<button class="demo" id="location" value="submit">Get location</button>
Now, if you run the above HTML, then you will get the following output in the browser.

Approach1 - Notice that our checkbox value and checkbox label text are different here.
Our objective is to get the label text. What can we do about that? In the below script, we
are targeting the label element and who’s for attribute value is the ‘value’ of the
checkbox fields. And we are printing our results in the console.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#skillset').click(function () {
const CheckboxChecked = $
('input[name="skillset"]:checked').length;
console.log(`Total ${CheckboxChecked} checkboxes are checked`);
$('input[name="skillset"]:checked').each(function () {
let value = $(this).val();
let checkboxText = $(`label[for="${value}"]`).text();
console.log(`Checkbox value is ${value}`);
console.log(`Check box text is ${checkboxText}`);

})
});
$('#location').click(function () {
const CheckboxChecked = $
('input[name="location"]:checked').length;
console.log(`Total ${CheckboxChecked} checkboxes are checked`);
$('input[name="location"]:checked').each(function () {
let value = $(this).val();
let checkboxText = $(`label[for="${value}"]`).text();
console.log(`Checkbox value is ${value}`);
console.log(`Check box text is ${checkboxText}`);
})
});
});
</script>
Run the code, open the browser developer’s tool by pressing the F12 key and then select
the following checkboxes and click on the Get Skillset button and please have a look at
the browser console window as shown in the below image.
As you can see in the above image, it prints the Skillset text and values in the console.
Now, refresh the page, select the checkboxes and click on the Get location button as
shown in the below image. And this time you will see the location text and values in the
console.

Following is the complete code.


<section>
<form action="/">
<fieldset>
<legend>Skillset: </legend>
<label for="HTML">HTML5</label>
<input type="checkbox" name="skillset" value="HTML" />
<label for="CSS">CSS3</label>
<input type="checkbox" name="skillset" value="CSS" />
<label for="JavaScript">JS</label>
<input type="checkbox" name="skillset" value="JavaScript" />
<label for="jquery">jquery3.6</label>
<input type="checkbox" name="skillset" value="jquery" />
</fieldset>
<br>
<fieldset>
<legend>Preferred Interview Location </legend>
<label for="Kolkata">KOL</label>
<input type="checkbox" name="location" value="Kolkata" />
<label for="Bhubaneshwar">BBS</label>
<input type="checkbox" name="location"
value="Bhubaneshwar" />
<label for="Bangalore">BLR</label>
<input type="checkbox" name="location" value="Bangalore" />
<label for="Pune">PUN</label>
<input type="checkbox" name="location" value="Pune" />
</fieldset>
</form>
</section>
</br>
<button class="demo" id="skillset" value="submit">Get skillset</button>
<button class="demo" id="location" value="submit">Get location</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#skillset').click(function () {
const CheckboxChecked = $
('input[name="skillset"]:checked').length;
console.log(`Total ${CheckboxChecked} checkboxes are
checked`);
$('input[name="skillset"]:checked').each(function () {
let value = $(this).val();
let checkboxText = $(`label[for="${value}"]`).text();
console.log(`Checkbox value is ${value}`);
console.log(`Check box text is ${checkboxText}`);
})
});
$('#location').click(function () {
const CheckboxChecked = $
('input[name="location"]:checked').length;
console.log(`Total ${CheckboxChecked} checkboxes are
checked`);
$('input[name="location"]:checked').each(function () {
let value = $(this).val();
let checkboxText = $(`label[for="${value}"]`).text();
console.log(`Checkbox value is ${value}`);
console.log(`Check box text is ${checkboxText}`);
})
});
});
</script>
Approach2: Notice that our program is working fine. But there is again the same
problem as the previous article. We are creating different handlers for different buttons.
What if there are many checkbox groups in our form? Will we create a different handler
to get the values of every checkbox group?
No, instead of this, we can create a function and pass a parameter to that as in the
previous article. That parameter will dynamically change the value of the name attribute
and we will invoke that function by just using two different parameters. The following
jQuery code exactly does the same.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#skillset').click(function () {
getCheckedValues('skillset');
});
$('#location').click(function () {
getCheckedValues('location');
});
function getCheckedValues(nameAttr) {
const CheckboxChecked = $("input[name='" + nameAttr +
"']:checked").length;
console.log(`Total ${CheckboxChecked} checkboxes are checked`);
$.each($("input[name='" + nameAttr + "']:checked"), function ()
{
let value = $(this).val();
let checkboxText = $(`label[for="${value}"]`).text();
console.log(`Checkbox value is ${value}`);
console.log(`Check box text is ${checkboxText}`);
});
}
});
</script>
With the above changes, we will achieve the desired output but the length of our code is
minimal.
jQuery Selected Selector
What is jQuery Selected Selector?
Previously we have seen that how to get the checked values of radio or checkbox
elements. Now we will see that how to get the values of the dropdown list in jQuery. We
use the checked selector in radio or checkbox elements. Now for the <option> element if
we have to get the option that the user has selected, then we need to use this selected
selector.
Syntax: $(‘select option:selected’): This will target the option elements which are
children of <select> and which are selected
Note: Because :selected is a jQuery extension and not part of the CSS specification,
queries using :selected cannot take advantage of the performance boost provided by the
native DOM querySelectorAll() method. To achieve the best performance when
using :selected to select elements, first select the elements using a pure CSS selector,
then use .filter(“:selected”).
Example: Extracting value of the Radio button - In the below example, we have a
basic dropdown list. We have attached a change() event to the <select> element of class
‘selectcountry’. Whenever we will make any change in the dropdown list, the method will
be triggered. Inside that, we are targeting those options which are selected by the user
and alerting them
<section>
<form action="/">
<fieldset>
<label>Select the country</label>
<select name="select" class="selectcountry">
<option value="USA">United States of America</option>
<option value="IND">India</option>
<option value="UK">United Kingdom</option>
</select>
</fieldset>
</form>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".selectcountry").change(function () {
var selectedCountry = $(".selectcountry
option:selected").val();
alert("You have selected the country - " + selectedCountry);
});
});
</script>
Once you run the above HTML code, you will get the following HTMP Page in the
browser.

Now, from the above dropdown list select India and as soon as you select India, the
change event is fired and you will get the following alert.
Once you click on the OK button, look at the dropdown list, the selected option is
changed to India as shown below.

Example2: Extracting text of the radio button


In the previous example, we are extracting the value of the option element. If we want to
retrieve the text inside the option element then we have to change the val() method to
the text() method which is shown in the below example.
<section>
<form action="/">
<fieldset>
<label>Select the country</label>
<select name="select" class="selectcountry">
<option value="USA">United States of America</option>
<option value="IND">India</option>
<option value="UK">United Kingdom</option>
</select>
</fieldset>
</form>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".selectcountry").change(function () {
var selectedCountry = $(".selectcountry
option:selected").text();
alert("You have selected the country - " + selectedCountry);
});
});
</script>
Now, save the changes and refresh the web page, and then select the United Kingdom
from the dropdown list and as soon as you select the United Kingdom, you will get the
following alert which shows the text of the selected option element i.e. United Kingdom.

Example3: Selecting multiple options from the dropdown list - In the previous
examples, we are having the dropdown lists from which only one option can be selected.
What if there is a multiple selected dropdown? In the below example, we are creating an
empty array. And for each selected option by the user, we are pushing the option text
into our array and alerting the final result.
<section>
<form action="/">
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="selectposition" multiple>
<option value="webdev">Web Developer</option>
<option value="webdesg">Web Designer</option>
<option value="graphic">Graphic Designer</option>
<option value="business">Business Analyst</option>
<option value="telecall">Telecaller Executive</option>
</select>
</fieldset>
</form>
</section>
</br>
<button class="demo" value="submit">Submit</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
var positions = [];
$.each($(".selectposition option:selected"), function () {
positions.push($(this).text());
});
alert("You have selected the positions - " +
positions.join(", "));
});
});
</script>
Now, run the above code and you will get the following HTML Page.

Now select multiple options from the dropdown list and click on the submit button as
shown in the below image. To select multiple options, hold down the CTRL key and select
the options.
Now, as soon as, you click on the Submit button, you will get the alert box with selected
options text value as shown in the below image.

Example4: More one dropdown list - When we have more than one dropdown list,
then what can we do? Let see that. In the below example, we have two <select>
elements with two different classes (position and tech). We are creating a function and
passing a parameter ‘className’ and when we are invoking the function, we are
changing the class names dynamically i.e. position and tech.
<section>
<form action="/">
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position" multiple>
<option value="webdev">Web Developer</option>
<option value="webdesg">Web Designer</option>
<option value="graphic">Graphic Designer</option>
<option value="business">Business Analyst</option>
<option value="telecall">Telecaller Executive</option>
</select>
</fieldset>
</br>
<fieldset>
<legend>Select the technologies you know</legend>
<select name="tech" class="tech" multiple>
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="jquery">jQuery</option>
<option value="react">React JS</option>
<option value="angular">Angular</option>
</select>
</fieldset>
</form>
</section>
</br>
<button class="demo" value="submit" id="position">Get positions</button>
<button class="demo" value="submit" id="tech">Get technologies</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button#position").click(function () {
getOptions('.position');
});
$("button#tech").click(function () {
getOptions('.tech');
});
function getOptions(className) {
var options = [];
$.each($(`${className} option:selected`), function () {
options.push($(this).text());
});
alert("You have selected the options - " + options.join(",
"));
}
});
</script>
Now, run the above code and you should get the following page in the browser.

Now, select some options from both the dropdown list. Here, I have selected two options
from the position dropdown list as well as two options from the technologies dropdown
list.
Once you selected the options, then click on the Get positions button. As soon as you click
on the Get positions button, it will show you the following alert.

As you can see in the above image, it is showing the text of the position that we have
selected in the positions dropdown list. Then click on the Ok button from the alert box.
Now, click on the Get technologies button and as soon as you click on the Get
technologies button, it will popup the following alert box with selected technologies text.

jQuery Disabled and Enabled Selector


jQuery Disabled Selector with Examples
jQuery disabled selector targets any element which is disabled. Disabled selector only
works with that elements which support the disabled attribute such as <input>,
<button>, <optgroup>, <select>, <fieldset>, <textarea>, etc.
Syntax:
1. $(‘:disabled’): This will target all elements that are disabled
2. $(‘input:disabled’): This will target all input elements that are disabled
3. $(‘:input:disabled’): This will target all input fields including <select>, <button>,
<textarea> etc that are disabled [Same as $( ‘:disabled’)]
Note: In our jQuery $(‘input’) vs $(‘:input’) Selectors article we have learnt the
difference between input selector and :input selector. Let us understand jQuery disabled
selector with some examples.
Example1: $(‘:disabled’)
In the below example, we are printing the jQuery object returned by $(‘:disabled’). Notice
that all the input fields which have the disabled attribute are present in the object.
<section>
<form action="/">
<fieldset>
<legend>Name: </legend>
<input type="text" name="Name" placeholder="Enetr Your Name"
disabled />
</fieldset>
<fieldset>
<legend>Email: </legend>
<input type="email" name="Email" placeholder="Enetr Your
Email" disabled />
</fieldset>
<fieldset>
<legend>Skillset: </legend>
<label for="HTML">HTML5</label>
<input type="checkbox" name="skillset" value="HTML" />
<label for="CSS">CSS3</label>
<input type="checkbox" name="skillset" value="CSS" />
<label for="JavaScript">JavaScript</label>
<input type="checkbox" name="skillset" value="JavaScript" />
<label for="jquery">jQuery</label>
<input type="checkbox" name="skillset" value="jQuery" />
</fieldset>
<fieldset>
<legend>Enter your DOB</legend>
<input type="datetime-local" name="datetime" />
</fieldset>
<fieldset>
<legend>Upload your Photo: </legend>
<input type="file" name="file" value="file" />
</fieldset>
<fieldset>
<legend>Years of experience: </legend>
<input type="number" name="number" />
</fieldset>
<fieldset>
<legend>Password: </legend>
<input type="password" name="password" />
</fieldset>
<fieldset>
<legend>Select Your Gender</legend>
<label>Male:
<input type="radio" name="radiogroup" value="Male"
/></label>
<label>Female:
<input type="radio" name="radiogroup" value="Female"
/></label>
</fieldset>
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position" multiple disabled>
<option value="webdev">Web Developer</option>
<option value="webdesg">Web Designer</option>
<option value="graphic">Graphic Designer</option>
<option value="business">Business Analyst</option>
<option value="telecall">Telecaller Executive</option>
</select>
</fieldset>
<fieldset>
<legend>Any other comments</legend>
<textarea name="textarea" rows="3" cols="20"
disabled></textarea>
</fieldset>
</form>
</section>
</br>
<button class="demo" value="submit">Submit</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
let disabledElem = $(':disabled');
console.log(disabledElem)
})
});
</script>
Now open browser developer tools by pressing the F12 key and have a look at the
console tab. Now, click on the Submit button and notice that all the input fields which
have the disabled attribute are present in the object are returned.

Example2: $(‘disabled’) - In the below example, we are applying a red border to the
elements which are disabled when we click on the submit button.
<section>
<form action="/">
<fieldset>
<legend>Name: </legend>
<input type="text" name="Name" placeholder="Enetr Your Name"
disabled />
</fieldset>
<fieldset>
<legend>Email: </legend>
<input type="email" name="Email" placeholder="Enetr Your
Email" disabled />
</fieldset>
<fieldset>
<legend>Skillset: </legend>
<label for="HTML">HTML5</label>
<input type="checkbox" name="skillset" value="HTML" />
<label for="CSS">CSS3</label>
<input type="checkbox" name="skillset" value="CSS" />
<label for="JavaScript">JavaScript</label>
<input type="checkbox" name="skillset" value="JavaScript" />
<label for="jquery">jQuery</label>
<input type="checkbox" name="skillset" value="jQuery" />
</fieldset>
<fieldset>
<legend>Enter your DOB</legend>
<input type="datetime-local" name="datetime" disabled />
</fieldset>
<fieldset>
<legend>Upload your Photo: </legend>
<input type="file" name="file" value="file" />
</fieldset>
<fieldset>
<legend>Years of experience: </legend>
<input type="number" name="number" disabled />
</fieldset>
<fieldset>
<legend>Password: </legend>
<input type="password" name="password" />
</fieldset>
<fieldset>
<legend>Select Your Gender</legend>
<label>Male:
<input type="radio" name="radiogroup" value="Male"
/></label>
<label>Female:
<input type="radio" name="radiogroup" value="Female"
/></label>

</fieldset>
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position" multiple disabled>
<option value="webdev">Web Developer</option>
<option value="webdesg">Web Designer</option>
<option value="graphic">Graphic Designer</option>
<option value="business">Business Analyst</option>
<option value="telecall">Telecaller Executive</option>
</select>
</fieldset>
<fieldset>
<legend>Any other comments</legend>
<textarea name="textarea" rows="3" cols="20"
disabled></textarea>
</fieldset>
</form>
</section>
</br>
<button class="demo" value="submit">Submit</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
let disabledElem = $(':disabled');
disabledElem.css('border','2px solid red')
})
});
</script>
Now, run the above HTML code and then click on the Submit button and you should see
the following output in the browser. Here, it applied a red border to the element which
has disabled property.
Example3: $(‘input:disabled’) - What will happen if we use $(‘input:disabled’)? Then
only those elements will be targeted which have the <input> tags and which are
disabled. Let us modify the script section of the previous as follows. The point that you
need to remember is that <textrea>, <select> is also disabled but the border has been
removed from them.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
let disabledElem = $('input:disabled');
disabledElem.css('border','2px solid red')
})
});
</script>
Now, save the above changes and run the code and then click on the Submit button and
you should get the following output in the browser.
Example4: $(‘:input:disabled’) - Now if we use $(‘:input:disabled’) then again all input
fields will be selected and the border will be applied. This will behave the same as
Example 2. Let proves this. Modify the script section as shown below.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
let disabledElem = $(':input:disabled');
disabledElem.css('border','2px solid red')
})
});
</script>
With the above changes in place, run the code and then click on the Submit button and
you should get the following output in the browser.
jQuery Enabled Selector with Examples: jQuery enabled selector targets any element
which is enabled. That means this will select elements that don’t have the disabled
attribute present.
Syntax:
1. $(‘:enabled’): This will target all elements that are enabled
2. $(‘input:enabled’): This will target all input elements that are enabled
3. $(‘:input:enabled’): This will target all input fields including <select>, <button>,
<textarea>, etc that are enabled [Same as $(‘:enabled’)]
Example1: Let us understand jQuery Enabled selector with some examples.
<section>
<form action="/">
<fieldset>
<legend>Name: </legend>
<input type="text" name="Name" placeholder="Enetr Your Name"
disabled />
</fieldset>
<fieldset>
<legend>Email: </legend>
<input type="email" name="Email" placeholder="Enetr Your
Email" disabled />
</fieldset>
<fieldset>
<legend>Enter your DOB</legend>
<input type="datetime-local" name="datetime" disabled/>
</fieldset>
<fieldset>
<legend>Upload your Photo: </legend>
<input type="file" name="file" value="file" />
</fieldset>
<fieldset>
<legend>Years of experience: </legend>
<input type="number" name="number" disabled/>
</fieldset>
<fieldset>
<legend>Password: </legend>
<input type="password" name="password" />
</fieldset>
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position" multiple>
<option value="webdev">Web Developer</option>
<option value="webdesg">Web Designer</option>
<option value="graphic">Graphic Designer</option>
<option value="business">Business Analyst</option>
<option value="telecall">Telecaller Executive</option>
</select>
</fieldset>
<fieldset>
<legend>Any other comments</legend>
<textarea name="textarea" rows="3" cols="20"
disabled></textarea>
</fieldset>
</form>
</section>
</br>
<button class="demo" value="submit">Submit</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
let enabledElem = $(':enabled');
enabledElem.css('border','2px solid red')
})
});
</script>
Now run the above code and click on the Submit button and you should get the following
output.

Look that those elements are targeted who don’t have the disabled attribute. But there is
a problem, <fieldset> also supports the disabled attributes. So by $(‘:enabled’) those
<fieldset> elements are also targeted here. In order to exclude <fieldset> from our
desired list of elements we have to use :not() selector. So, modify the script section as
follows.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
let enabledElem = $(':enabled:not("fieldset")');
enabledElem.css('border','2px solid red')
})
});
</script>
Now our problem is solved. Run the code and you will get the following output.
Example2: $(‘input:enabled’) - Now if we use $(‘input:enabled’) then only those
<input> tags will be selected which don’t have the disabled attribute. So, modify the
script section as follows and see the output. In the below example, <select>, <textarea>
are also enabled but they are not targeted at all. Moreover, there is no need of
using :not(‘fieldset’ ), because the fieldset is not an input element.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
let enabledElem = $('input:enabled');
enabledElem.css('border','2px solid red')
})
});
</script>
With the above changes in place, run the code and click on the Submit button and you
should get the following output.
Example3: $(‘:input:enabled’) - Now if we use $(‘:input:enabled’) then again all input
fields will be selected which do not have the disabled attribute and the border will be
applied. Below is the example.
<section>
<form action="/">
<fieldset>
<legend>Name: </legend>
<input type="text" name="Name" placeholder="Enetr Your Name"
disabled />
</fieldset>
<fieldset>
<legend>Email: </legend>
<input type="email" name="Email" placeholder="Enetr Your
Email" disabled />
</fieldset>
<fieldset>
<legend>Enter your DOB</legend>
<input type="datetime-local" name="datetime" disabled/>
</fieldset>
<fieldset>
<legend>Upload your Photo: </legend>
<input type="file" name="file" value="file" />
</fieldset>
<fieldset>
<legend>Years of experience: </legend>
<input type="number" name="number" disabled/>
</fieldset>
<fieldset>
<legend>Password: </legend>
<input type="password" name="password" />
</fieldset>
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position" multiple>
<option value="webdev">Web Developer</option>
<option value="webdesg">Web Designer</option>
<option value="graphic">Graphic Designer</option>
<option value="business">Business Analyst</option>
<option value="telecall">Telecaller Executive</option>
</select>
</fieldset>
<fieldset>
<legend>Any other comments</legend>
<textarea name="textarea" rows="3" cols="20"
disabled></textarea>
</fieldset>
</form>
</section>
</br>
<button class="demo" value="submit">Submit</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
let enabledElem = $(':input:enabled');
enabledElem.css('border','2px solid red')
})
});
</script>
Now, run the above code and click on the Submit button and you should get the following
output.
jQuery Each Method
jQuery Each Method
The jQuery Each method is used to iterate over the items of a collection. This iterates
over a jQuery object executing a function for each element of the collection. For each
item in the collection, the anonymous
function is called. The index of the element
and the element itself is passed to the
anonymous function. Following is the syntax
to use the jQuery Each method.
The jQuery each() method takes a callback function which takes two optional parameters
Index and the current DOM element i.e. the current item or element over which the
iteration is going. Each time the callback runs, it is passed the current loop iteration,
beginning from 0. Let us understand the need and use of jQuery each function with
examples.
Example: In the below example, we have 3 <div> elements. By using each() method, we
are iterating over those and for each div element, we are printing the index, their ID, and
the text inside them on the console.
<h3>jQuery Each Method</h3>
<section>
<div id="1st">This is 1st text</div>
<div id="2nd">This is 2nd text</div>
<div id="3rd">This is 3rd text</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('div').each(function(index, item){
console.log(`${index} ${$(item).attr('id')} ${$
(item).text()}`)
});
});
});
</script>
Now, open the browser developer tool by pressing the F12 key and open the console tab.
Then click on the Click Me button and you should get the following log in the console tab.

The callback is fired in the context of the current DOM element, the keyword ‘this’ refers
to the element. So, we can use this keyword instead of the item parameter. Modify the
script section of the previous example as shown below and it should work as expected as
the previous example.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$( 'div' ).each(function(index){
console.log(`${index} ${$(this).attr('id')} ${$
(this).text()}`)
});
});
});
</script>
Example: In the below example, we are applying CSS to every <div> element present in
our DOM
<h3>jQuery Each Method</h3>
<section>
<div id="1st">This is 1st text</div>
<div id="2nd">This is 2nd text</div>
<div id="3rd">This is 3rd text</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('div').each(function(){
$(this).css('backgroundColor','skyblue')
});
});
});
</script>
Now, run the above code and then click on the Click Me button and you should get the
following output in the browser.

Exit from Iteration using jQuery - If we want to exit from the loop at any stage of the
iteration then we need to use {return false}. In the below example, as soon as the div
text is matching with “This is 5 th text”, our loop ends there immediately. Notice that the
iteration has been performed only with 4 div elements
<h3>Exit From jQuery Each Method</h3>
<section>
<div id="1st">This is 1st text</div>
<div id="2nd">This is 2nd text</div>
<div id="3rd">This is 3rd text</div>
<div id="4th">This is 4th text</div>
<div id="5th">This is 5th text</div>
<div id="6th">This is 6th text</div>
<div id="7th">This is 7th text</div>
<div id="8th">This is 8th text</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('div').each(function () {
if ($(this).text() === 'This is 5th text')
{
return false
}
$(this).css('backgroundColor', 'skyblue')
});
});
});
</script>
Now, run the above code and then click on the Click Me button and you should get the
following output in the browser and notice that the CCS is applied up to the fourth div
element.

Implicit Iteration in jQuery - Most jQuery methods that return a jQuery object also
loop through the set of elements in the jQuery collection, a process known as implicit
iteration. When this occurs, it is often unnecessary to explicitly iterate with the .each()
method. Let’s see an example.
<h3>Implicit Iteration in jQuery</h3>
<section>
<ul>
<li>This is a list</li>
<li>This is a list</li>
<li>This is a list</li>
<li>This is a list</li>
<li>This is a list</li>
<li>This is a list</li>
</ul>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('li').each(function () {
$(this).css('color', 'red');
});
});
});
</script>
Now, run the above code and then click on the Click Me button and you should get the
following output in the browser

Here, we are explicitly adding a CSS to every <li> element. But here $( ‘li’ ) returns a
collection in which we can directly apply the CSS. This will iterate over every list item
implicitly. To do so, please modify the script section as shown below.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('li').css('color', 'red')
});
});
</script>
With the above changes in place, if you run the code, then you will get the same output as
the previous example as shown in the below image.
jQuery.each() Utility function
The jQuery.each() Utility function is a generic iterator function, which can be used to
seamlessly iterate over both objects and arrays.
Difference between $(‘selector ).each and $.each(): The $.each() function is not the
same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object.
The $.each() function can be used to iterate over any collection, whether it is an object or
an array. In the case of an array, the callback is passed an array index and a
corresponding array value each time. (The value can also be accessed through
this keyword, but JavaScript will always wrap this value as an Object even if it is a simple
string or number value.) The method returns its first argument, the object that was
iterated.
Syntax:

Let us understand this with some examples.


Example: jQuery.each() Method with array
In the below example, we have an array and we can access all of its element by this
$.each() function
<h3>jQuery Each Function</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = ["HTML","CSS","JavaScript","jQuery","React"];
$.each(arr, function(index, item){
console.log(`Index no ${index} : Item = ${item}`)
});
});
</script>
Now run the above code and then open the browser developer tool by pressing the F12
key and have a look at the console and you should see the following logs in the console.
Example: jQuery.each() Method with object - In the below example, we have an
object and we can access all of its key and value pair by using the $.each() function.
<h3>jQuery Each Function</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let obj ={
name : 'John',
age : 22,
job : 'Web Developer',
hobby : 'cricket',
}
$.each( obj, function(key, val){
console.log( `Key = ${key} : Value = ${val}` )
});
});
</script>
Now run the above code and then open the browser developer tool by pressing the F12
key and have a look at the console and you should see the following message in the
console.

Performance considerations when using jQuery each Method


Let us understand this with an example. Please have a look at the below code.
<ul>
<li>JavaScript</li>
<li>jQuery</li>
<li>Angular</li>
<li>ReactJS</li>
<li>NodeJS</li>
</ul>
<div id="ResultDiv"></div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('li').each(function () {
$('#ResultDiv').html($('#ResultDiv').html() + '<br/>' + $
(this).text())
});
});
</script>
From a performance point of view, there are 2 problems with the above code.
1. First Problem: The jQuery needs to search the DOM for div element with id
ResultDiv, for each list item in the collection. As we have 5 list items, the jQuery
searches the DOM 5 times for the same div element with id ResultDiv. We can
improve the performance of the above code \ by caching the ResultDiv element.
2. Second Problem: The DOM element (div element with id ResultDiv) is updated for
each iteration. Again, this is bad for performance. To improve the performance, we
can build a string variable with the required data on each iteration. Once the loop has
been completed, update the DOM element with the value that is present in the string
variable. This will ensure that the DOM element (div element with id ResultDiv) is
updated only once and this is much better for performance.
The following code addresses the above two problems and provides much better
performance.
<ul>
<li>JavaScript</li>
<li>jQuery</li>
<li>Angular</li>
<li>ReactJS</li>
<li>NodeJS</li>
</ul>
<div id="ResultDiv"></div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
var result = '';
$('li').each(function () {
result += '<br/>' + $(this).text();
});
$('#ResultDiv').html(result);
});
</script>
jQuery Method Chaining
jQuery Method Chaining
JQuery provides another robust feature called method chaining that allows us to perform
multiple actions on the same set of elements, all within a single line of code. This is
possible because most of the jQuery methods return a jQuery object that can be further
used to call another method.
Syntax: $(‘selector’).method1().method2().method3()………………..
Thus, you can add multiple methods to one set of elements. Let us understand jQuery
Method Chaining with some examples.
Example: Now if we have to perform multiple methods to one set of elements what can
we do? In the below example, to the <div> element we are performing 5 animation
methods consecutively.
<h3>jQuery Method Chaining</h3>
<section>
<div class="div1">
<h4>This is a Title</h4>
jQuery is a fast, small, lightweight, and feature-rich JavaScript
library. It is designed to simplify the client-side scripting of HTML. It
makes things like DOM traversal and manipulation, event handling, animation,
and Ajax much simpler. With a combination of versatility and extensibility,
jQuery has changed the way that millions of people write JavaScript. As of
May 2019, jQuery was used by 73% of the 10 million most popular websites.
</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function(){
$('.div1').animate({height: "400px"},1000);
$('.div1').hide(1000);
$('.div1').show(1000);
$('.div1').slideUp(1000);
$('.div1').slideDown(1000);
})
});
</script>
Now run the above code and observe that when we will click on the Click Me button at
first the div will increase its height, then it will hide, then it will appear again, then will
side up and slide down. Thus, all the animations will be performed.
But in the above example, we are using different animations on the same element by
writing different lines of codes. See how we can transform this into a line of code by
jQuery Method Chaining. To do so, please modify the script section as shown below.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('.div1').animate({ height:
"500px" },1000).hide(1000).show(1000).slideUp(1000).slideDown(1000);
})
});
</script>
Now notice that we need not write different lines of codes. We can connect these
methods as above. This will perform exactly the same as the previous example. This is
called method chaining in jQuery.
Example: These animation methods return again the jQuery object. So, it is possible to
add further methods to that one. But what about those methods which return an object
like test(), html(), attr(). These methods are used to retrieve the inner text or Html or
attribute value of any element, they don’t return again an object. So, chaining will not
work on them. Let’s understand this with an example.
In the below method chain example, you will notice that at first the border has been
applied, then the height increases, and then the div disappears, but the text() method is
returning just a string, not an object. So, the show() method is not working on that. So
our chain breaks at hide() method
<h3>Query Method Chaining</h3>
<section>
<div class="div1">
jQuery is a fast, small, lightweight, and feature-rich JavaScript
library. It is designed to simplify the client-side scripting of HTML. It
makes things like DOM traversal and manipulation, event handling, animation,
and Ajax much simpler. With a combination of versatility and extensibility,
jQuery has changed the way that millions of people write JavaScript. As of
May 2019, jQuery was used by 73% of the 10 million most popular websites.
</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('.div1').css('border','2px solid blue').animate({ height:
"500px" },1000).hide(1000).text().show(1000);
})
});
</script>
Once you run the code, open the browser developer tool by pressing the F12 key and
then click on the Click Me button and have a look at the console tab and it will display
the error message saying that show is not a function as shown in the below image.
Example: By using the text(), html(), attr() methods, if we want to retrieve any value
then our method chaining will not work. But by these methods, if we want to set any text,
Html, or attribute then our jQuery Method Chaining will work perfectly. Let us
understand this with an example.
In the below example, the text() method sets the inner text of the div, the attr() method
sets the title attribute to ‘Sample Div’ and returning the object. So we can perform the
animation methods on them.
<h3>jQuery Method Chaining</h3>
<section>
<div class="div1">
jQuery is a fast, small, lightweight, and feature-rich JavaScript
library. It is designed to simplify the client-side scripting of HTML. It
makes things like DOM traversal and manipulation, event handling, animation,
and Ajax much simpler. With a combination of versatility and extensibility,
jQuery has changed the way that millions of people write JavaScript. As of
May 2019, jQuery was used by 73% of the 10 million most popular websites.
</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('.div1').css('border','2px solid blue').animate({ height:
"500px" },1000).hide(1000).text('This is sample text').attr('title','Sample
Div').show(1000);
})
});
</script>
Notice that all of the methods of our chain are performed here. Also, the title attribute
has been set.
Event Chaining in jQuery: jQuery not only supports method chaining but also supports
event chaining. We can attach multiple events to one set of elements. Let us understand
jQuery Event Chaining with some examples. In the below example. we are attaching two
events to a button at the same time by event chaining.
<h3>jQuery Event Chaining</h3>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').mouseover(function(){alert('Mouse
Over')}).mouseleave(function(){alert('Mouse Out')})
});
</script>
At first when we hovered on the button 1 st event-triggered and then the second one when
we left out the mouse.
Working with JSON Object
What is JSON?
1. JSON stands for JavaScript Object Notation.
2. JSON is a format for storing and transporting data
3. JSON is often used when data is sent from a server to a web page
4. JSON is a lightweight data-interchange format
5. JSON is language independent
6. JSON is easier than XML
JSON Syntax rules:
1. Data is in key/value pairs
2. Data is separated by commas
3. JSON objects are surrounded by curly braces {}
4. Curly braces hold objects
5. Square brackets hold arrays
The data type of JSON object’s value cannot be a date, function, or undefined. JSON
supports the following data types:
1. Objects { … }
2. Arrays [ … ]
3. Primitives:
4. strings,
5. numbers,
6. Boolean values true/false,
7. null.
Syntax:
Following is the syntax to create a JSON object.

Example: JSON Object


Let us understand how to work with JSON with examples. Let’s create a JSON Object first
as shown below.
<script>
var employee = {
"firstname" : "Rick",
"lastname" : "Brown",
"age" : 22,
"salary" : 15000
};
</script>
Here,
1. employee is the JSON object
2. In the curly braces, we include the property as “key”: “value” pairs, separated by
commas
3. The Key and value of a property must be separated by using a colon (:)
4. We can declare any number of properties inside a JSON object.
This is an example of a JSON object. Now if we want to access any of its value, then we
can do it in the following way. As you can see, to read data from the JSON object, we
need to use the object property names.
console.log(‘The First Name of the employee is ${employee.firstname}’);
console.log(‘The Last Name of the employee is ${employee.lastname}’);
console.log(‘The Salary of the employee is ${employee.salary}’);
Following is the complete code example.
<h3>Working with JSON</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
var employee = {
"firstname" : "Rick",
"lastname" : "Brown",
"age" : 22,
"salary" : 15000
};
console.log(`The First Name of the employee is ${employee.firstname}`);
console.log(`The Last Name of the employee is ${employee.lastname}`);
console.log(`The Age of the employee is ${employee.age}`);
console.log(`The Salary of the employee is ${employee.salary}`);
</script>
How to access the JSON Object elements using jQuery Each function?
We can also use the jQuery each() utility function to access the JSON Object elements.
For better understanding, please have a look at the below example, where we are
accessing all the elements of the employee JSON object using the jQuery each() function.
<h3>Working with JSON</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
var employee = {
"firstname" : "Rick",
"lastname" : "Brown",
"age" : 22,
"salary" : 15000
};
$.each( employee, function(prop, val){
console.log(`The property is ${prop} and the value is ${val}`)
});
</script>
Here, we are using each() method to access all the properties of an object in a loop.
JSON Array of Objects.
If you want to store more than one employee object in the JSON object, then we need to
create JSON Array. The JSON array can contain more than one JSON object.
Syntax to Create JSON Array of Objects
Wrap the objects in square brackets and each object must be separated with a comma.
For better understanding, please have a look at the below image which shows the syntax
to create a JSON array of objects.

Example: JSON Array of objects - Let us understand the JSON Array of objects with an
example. Let’s create a JSON Array of Objects first as shown below.
var employeeList = [{
"firstname": "Rick",
"lastname": "Brown",
"age": 22,
"salary": 15000
},

];
This is a JSON array of objects. Each element of the array is a JSON object. To access the
employee objects in the JSON array, we need to use the object’s index position and the
index position starts from 0. That is the first employee index position is 0 and second
employee object index position is 1 and so on.
Now if we have to access the 1st object then we have to use employeeList[0], and then if
we have to access the first name property of the 1 st object then we have to use
employeeList[0].firstname. The following code snippet shows how to access each element
of the first employee from the JSON array of objects.
console.log(`The First Name of the 1st employee is $
{employeeList[0].firstname}`);
console.log(`The Last Name of the 1st employee is $
{employeeList[0].lastname}`);
console.log(`The Age of the 1st employee is ${employeeList[0].age}`);
console.log(`The Salary of the 1st employee is ${employeeList[0].salary}`);
Similarly, if you want to access the 2nd t object then you have to use employeeList[1], and
then if you have to access the first name property of the 2nd object then you have to use
employeeList[1].firstname. The following code snippet shows how to access each element
of the second employee object from the JSON array of objects.
console.log(`The First Name of the 2nd employee is $
{employeeList[1].firstname}`);
console.log(`The Last Name of the 2nd employee is $
{employeeList[1].lastname}`);
console.log(`The Age of the 2nd employee is ${employeeList[1].age}`);
console.log(`The Salary of the 2nd employee is ${employeeList[1].salary}`);
But this is too lengthy. We can use the jQuery each() method to access our objects in a
loop as shown in the below example.
<h3>Working with JSON Array</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
var employeeList = [{
"firstname": "Rick",
"lastname": "Brown",
"age": 22,
"salary": 15000
},
{
"firstname": "John",
"lastname": "Doe",
"age": 24,
"salary": 12000
},
{
"firstname": "Sarah",
"lastname": "Tye",
"age": 25,
"salary": 17000
}];

$.each(employeeList, (index, item) => {


console.log(`Index no ${index} :- The Full Name of the employee is $
{item.firstname} ${item.lastname}.
His age is ${item.age} and salary is ${item.salary}`)
});
});
</script>
JSON Nested Object: It is also possible to store multiple JSON objects in the JSON
object by nesting them. Following is the syntax to store multiple JSON objects by nesting
them.
Example: Nested JSON Objects - Let us understand how to store multiple JSON
objects by nesting them with an example. Please have a look at the below code.
var employeeDetails = {
"Basic": {
"firstname": "Rick",
"lastname": "Brown",
"age": 22,
"salary": 15000
},
"Address": {
"Country": "India",
"State": "Odisha",
"City": "Bhubaneswar"
}
};
This is an example of a nested object. Here employeeDetails is an object. Basic and
Address are its property. Again, Basic and Address are objects.
The Basic property can be accessed by employeeDetails.Basic. This is again an object, so
the firstname property can be accessed as employeeDetails.Basic.firstname and in the
same way you can access the other properties.
The Address property can be accessed by employeeDetails.Address. As Address is again
an object, so the Country property can be accessed as employeeDetails.Address.Country
and in the same way you can access the other properties of the Address object.
Following is the complete code of the above-discussed example.
<h3>Working with Nexted JSON Object</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
var employeeDetails = {
"Basic": {
"firstname": "Rick",
"lastname": "Brown",
"age": 22,
"salary": 15000
},
"Address": {
"Country": "India",
"State": "Odisha",
"City": "Bhubaneswar"
}
};

console.log(`The First Name of the employee is $


{employeeDetails.Basic.firstname}`);
console.log(`The Last Name of the employee is $
{employeeDetails.Basic.lastname}`);
console.log(`The Age of the employee is ${employeeDetails.Basic.age}`);
console.log(`The Salary of the employee is $
{employeeDetails.Basic.salary}`);

console.log(`The Country of the employee is $


{employeeDetails.Address.Country}`);
console.log(`The State of the employee is $
{employeeDetails.Address.State}`);
console.log(`The City of the employee is $
{employeeDetails.Address.City}`);
</script>
Ye can also use the jQuery each() method to iterate through the properties of the nested
objects which is shown in the below example.
<h3>Working with Nexted JSON Object</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
var employeeDetails = {
"Basic": {
"firstname": "Rick",
"lastname": "Brown",
"age": 22,
"salary": 15000
},
"Address": {
"Country": "India",
"State": "Odisha",
"City": "Bhubaneswar"
}
};
$.each(employeeDetails, function(prop, val){
$.each(employeeDetails[prop], function( props, vals ){
console.log(` ${props} : ${vals} `);
});
});
</script>
Output:
Converting JSON Object to String and String to JSON Object
What is a JSON String?
JSON is an acronym for JavaScript Object Notation. JSON was designed as a data
interchange format and has a syntax that is a subset of JavaScript. Context which is
surrounded by quotes (single or double), loaded from a text file, etc. are called JSON
strings.
{“id”:1, “name”:”John”, “age”:22, “eyecolor”:”Blue”,
“profession”:”Accountant”}
JSON is interoperable meaning that it’s language/platform independent. The JSON format
is used for serializing and transmitting structured data over a network connection. It is
used primarily to transmit data between a server and mobile/web application, serving as
an alternative to XML.
When would you want to convert from JSON Object to JSON string?
A common use of JSON is to exchange data to/from a web server. When sending data to a
web server, the data has to be a string. Then we have to convert a JSON object into a
string with JSON.stringify().
Syntax: Use the JavaScript function JSON.stringify() to convert JSON Object (JSON
Array) it into a string.
var jsonString = JSON.stringify(obj);
Example: Converting JSON Object to JSON String - In the below example, we have
one JSON object i.e. employee. We are converting that JSON Object into a JSON string
and printing that JSON String on the console. Notice that we are also printing the Data
type of the JSON String.
<h3>Converting JSON Object to JSON String</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
const employee= {
"firstname": "Rick",
"lastname": "Brown",
"age": 22,
"salary": 15000
};
var string = JSON.stringify(employee);
console.log(string);
console.log(typeof string);
</script>
Now run the above code and open the browser developer tool by pressing the F12 key
and look at the Console tab where it logs the JSON string ({“firstname”:”Rick”,
“lastname”:”Brown”, “age”:22, “salary”:15000}) and the data type of the JSON string
(string).
Example: Converting JSON Array to a JSON String. In the below example we are
converting a JSON array to a string.
<h3>Converting JSON Object to JSON String</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
const employeeList= [{
"firstname": "Rick",
"lastname": "Brown",
"age": 22,
"salary": 15000
},
{
"firstname": "Rick",
"lastname": "Brown",
"age": 22,
"salary": 15000
}
];
var string = JSON.stringify(employeeList);
console.log(string);
console.log(typeof string);
</script>
When would you want to convert from JSON string to JSON object?
When receiving data from a web server, the data is always a string. Parse the data
with JSON.parse() method, and the data becomes a JSON object.
Use the JavaScript function JSON.parse() to convert it into an object.
var jsonObj = JSON.parse(string);
Example: Converting JSON String to JSON Object - In the below example, we have a
JSON string i.e. employee. We are converting that JSON string into a JSON object and
printing it on the console. Notice that we are also printing the Data type of the JSON
Object.
<h3>Converting JSON String to JSON Object</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
var employee= '{"firstname": "Rick", "lastname": "Brown", "age": 22,
"salary": 15000}';
var object = JSON.parse(employee);
console.log(object);
console.log(typeof object); // object
</script>
We can also print the properties and values of the object by using the jQuery
each() function. For better understanding, please have a look at the below
example.
<h3>Converting JSON String to JSON Object</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
const employee= '{"firstname": "Rick", "lastname": "Brown", "age": 22,
"salary": 15000}';
var object = JSON.parse(employee);
$.each(object, function(prop,val){
console.log(` ${prop} : ${val}`)
});
</script>
Parsing Functions in jQuery: We have learned in the previous article that Functions
are not allowed in JSON. If you need to include a function, you have to write it as a string.
You can convert it back into a function by eval() method later. For better understanding,
please have a look at the below example.
<h3>Parsing Functions in jQuery</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
const employee = '{"firstname": "Rick", "lastname": "Brown", "age":
"function() { return 22; }", "salary": 15000}';
let object = JSON.parse(employee);
object.age = eval(`(${object.age})`);
console.log(` The age of the employee is ${object.age()}`)
</script>
Output: The age of the employee is 22
Parsing Dates in jQuery: We have learned from the previous article that Date objects
are not allowed in JSON. If you need to include a date, you have to write it as a string.
You can convert it back into a date object later. For better understanding, please have a
look at the below example.
<h3>Parsing Functions in jQuery</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
const employee = '{"firstname": "Rick", "lastname": "Brown", "age":
22, "salary": 15000, "DOB": "1997-05-15"}';
let object = JSON.parse(employee);
object.DOB = new Date(object.DOB);
console.log(`The DOB of the employee is ${object.DOB}`)
</script>
Output: The DOB of the employee is Thu May 15 1997 05:30:00 GMT+0530
(India Standard Time)
You can also use the second parameter, of the JSON.parse() function, called reviver.
The reviver parameter is a function that checks each property, before returning the
value. For better understanding, please have a look at the below example.
<h3>Parsing Functions in jQuery</h3>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
const employee = '{"firstname": "Rick", "lastname": "Brown", "age":
22, "salary": 15000, "DOB": "1997-05-15"}';
let object = JSON.parse(employee, function (key, value) {
if (key == "DOB") {
return new Date(value);
} else {
return value;
}
});
console.log(`The DOB of the employee is ${object.DOB}`)
</script>
In the above example, we are converting a string into a date by the reviver function. You
will get the same output as the previous example.
jQuery DOM Manipulation Methods
jQuery DOM Manipulation Methods
jQuery provides methods to manipulate DOM in an efficient way. We do not need to write
big code to modify the value of any element’s attribute or to extract HTML code from a
paragraph or division.
A few of them simply change one of the attributes of an element, while others set an
element’s style properties. Still, others modify entire elements (or groups of elements)
themselves inserting, copying, removing, and so on. All of these methods are referred to
as “setters,” as they change the values of properties.
A few of these methods such as .attr(), .html(), and .val() also act as “getters,” retrieving
information from DOM elements for later use. All these methods are listed below.
1. .addClass(): Adds the specified class(es) to each element in the set of matched
elements..
2. .after(): Insert content, specified by the parameter, after each element in the set of
matched elements.
3. .append(): Insert content, specified by the parameter, to the end of each element in
the set of matched elements.
4. .appendTo(): Insert every element in the set of matched elements to the end of the
target.
5. .attr(): Get the value of an attribute for the first element in the set of matched
elements or set one or more attributes for every matched element.
6. .before(): Insert content, specified by the parameter, before each element in the set
of matched elements.
7. .clone(): Create a deep copy of the set of matched elements
8. .css(): Get the value of a computed style property for the first element in the set of
matched elements or set one or more CSS properties for every matched element.
9. .detach(): Remove the set of matched elements from the DOM.
10. .empty(): Remove all child nodes of the set of matched elements from the DOM.
11. .hasClass(): Determine whether any of the matched elements are assigned the
given class
12. .height(): Get the current computed height for the first element in the set of
matched elements or set the height of every matched element.
13. .html(): Get the HTML contents of the first element in the set of matched
elements or set the HTML contents of every matched element.
14. .innerHeight(): Get the current computed inner height (including padding but not
the border) for the first element in the set of matched elements or set the inner height
of every matched element.
15. .innerWidth(): Get the current computed inner width (including padding but not
the border) for the first element in the set of matched elements or set the inner width
of every matched element.
16. .insertAfter(): Insert every element in the set of matched elements after the
target.
17. .insertBefore(): Insert every element in the set of matched elements before the
target.
18. Jquery.cssNumber: An object containing all CSS properties that may be used
without a unit. The .css() method uses this object to see if it may append px to unitless
values..
19. Jquery.htmlPrefilter: Modify and filter HTML strings passed through jQuery
manipulation methods.
20. .offset(): Get the current coordinates of the first element, or set the coordinates of
every element, in the set of matched elements, relative to the document.
21. .outerHeight(): Get the current computed outer height (including padding,
border, and optionally margin) for the first element in the set of matched elements or
set the outer height of every matched element.
22. .outerWidth(): Get the current computed outer width (including padding, border,
and optionally margin) for the first element in the set of matched elements or set the
outer width of every matched element.
23. .position(): Get the current coordinates of the first element in the set of matched
elements, relative to the offset parent.
24. .prepend(): Insert content, specified by the parameter, to the beginning of each
element in the set of matched elements.
25. .prependTo(): Insert every element in the set of matched elements to the
beginning of the target.
26. .prop(): Get the value of a property for the first element in the set of matched
elements or set one or more properties for every matched element.
27. .remove(): Remove the set of matched elements from the DOM.
28. .removeAttr(): Remove an attribute from each element in the set of matched
elements.
29. .removeClass(): Remove a single class, multiple classes, or all classes from each
element in the set of matched elements.
30. .removeProp(): Remove a property for the set of matched elements.
31. .replaceAll(): Replace each target element with the set of matched elements.
32. .replaceWith(): Replace each element in the set of matched elements with the
provided new content and return the set of elements that were removed.
33. .scrollLeft(): Get the current horizontal position of the scroll bar for the first
element in the set of matched elements or set the horizontal position of the scroll bar
for every matched element.
34. .scrollTop(): Get the current vertical position of the scroll bar for the first element
in the set of matched elements or set the vertical position of the scroll bar for every
matched element.
35. .text(): Get the combined text contents of each element in the set of matched
elements, including their descendants, or set the text contents of the matched
elements.
36. .toggleClass(): Add or remove one or more classes from each element in the set
of matched elements, depending on either the class’s presence or the value of the
state argument.
37. .unwrap(): Remove the parents of the set of matched elements from the DOM,
leaving the matched elements in their place.
38. .val(): Get the current value of the first element in the set of matched elements or
set the value of every matched element.
39. .width(): Get the current computed width for the first element in the set of
matched elements or set the width of every matched element.
40. .wrap(): Wrap an HTML structure around each element in the set of matched
elements.
41. .wrapAll(): Wrap an HTML structure around all elements in the set of matched
elements.
42. .wrapInner(): Wrap an HTML structure around the content of each element in the
set of matched elements.
Note: In our previous examples, we have used many of these methods such val(), text(),
html()….. In the upcoming articles, we will discuss all of these DOM manipulation
methods. In this article, let’s pick the attr() method.
jQuery attr() Method
The attr() method sets or returns attributes and values of the selected elements. It can be
used as both getter and setter. When this method is used to return the attribute value, it
returns the value of the FIRST matched element. When this method is used
to set attribute values, it sets one or more attribute/value pairs for the set of matched
elements.
Syntax:
Example: jQuery DOM Manipulation Methods - In the below example, we want to
return the ‘title’ attribute values of the div elements. But notice that by $(‘div’).attr()
method, we are getting only the 1st attribute value of the matching set of elements
<h3>jQuery DOM Manipulation</h3>
<section>
<div title="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="div2">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="div3">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
console.log($('div').attr('title')); // div1
})
})
</script>
To get all the title attribute values we have to iterate over the div elements. To do so,
modify the Script section as shown below.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('div').each(function () {
console.log($(this).attr('title')); //div1 div2 div3
})
})
})
</script>
Example: Setting Attribute Value using Attr method - In the below example, the
attr() method is implicitly iterating over the matching div elements and setting the title
attribute values to ‘mySampleDiv’. Notice that, if you hover on any of the div elements
you will see the title ‘mySampleDiv’.
<h3>jQuery DOM Manipulation</h3>
<section>
<div title="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="div2">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="div3">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('div').attr('title','mySampleDiv')
});
});
</script>
Now run the above code. Then click on the Click Me button and then mouse over on any
of the div elements and you will see that the title attribute is changed to ‘mySampleDiv’
as shown in the below example.
Example: Setting Attribute Value using Callback function in jQuery
In the below example, we will use the callback function to set the title attribute value.
<h3>jQuery DOM Manipulation</h3>
<section>
<div title="sampleDiv">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="sampleDiv">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="sampleDiv">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('div').attr('title', function (index, prevVal) {
return prevVal + index;
});
});
</script>
Notice carefully in the above example. Here we are using callback in attr() method. The
function takes two parameters
1. index of the element currently iterating over
2. the previous value of the title attribute.
We are concatenating index no with the previous value of the attribute. Now, run the
above code and then click on the Click Me button and then check the div element title
attribute as shown in the below image.
Example: Setting Multiple Attribute Values using jQuery Attr DOM Manipulation
Method
In this example, we will see that how to set the multiple attribute values.
<h3>jQuery DOM Manipulation</h3>
<section>
<div title="sampleDiv1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="sampleDiv2">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="sampleDiv3">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('div').attr({
'title': 'MyDiv',
'style': 'border:2px solid black; background-color: skyblue; border-
radius: 30px ',
});
});
$('.demo').click(function () {
$('div').each(function () {
console.log($(this).attr('title'));
});
});
</script>
In the case of setting multiple attribute values, you have to pass it as a JSON object. In
this example, we are setting the title as well as the style attribute value. Notice that our
style of the div elements has been changed and the title attribute value is also changed
which is printed on the console.
Example: Remove an attribute using jQuery removeAttr() method
To remove an attribute, we need to use the removeAttr function. In the below example,
we remove the title attribute from all the div elements.
<h3>jQuery DOM Manipulation</h3>
<section>
<div title="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="div2">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
<div title="div3">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione
quod
</div>
</section>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('.demo').click(function () {
$('div').each(function () {
$(this).removeAttr('title');
})
})
})
</script>
jQuery Wrap and UnWrap Elements
jQuery Wrap and UnWrap Elements
The following four jQuery methods are used to wrap and unwrap the HTML elements. As
these methods are used to modify the DOM elements, they belong to the DOM
manipulation category.
1. Wrap
2. Unwrap
3. wrapAll
4. wrapInner
jQuery wrap() method
The wrap() method is an inbuilt method in jQuery that is used to wrap the specified
element around the selected element. Suppose you have a span element as follows
<span>This is a text</span>, you want to wrap this element inside a div element like
<div>
<span>This is a text</span>
</div>
Then you have to use the jQuery wrap method.
Syntax: $(selector).wrap(element, function)
Parameters: This method accepts two parameters as follows:
1. element: It is a required parameter that is used to specify the element to wrap
around the selected elements. Possible values are HTML elements, jQuery objects,
DOM elements
2. function: It is an optional parameter that is used to specify the function which
returns the wrapping element.
Example: jQuery wrap method औ Let us understand the jQuery wrap method with
examples. In the below example, we have an <div> element. And when we will click on
the Click Me button the div element will be wrapped around an <section> element.
<h3>jQuery wrap Method</h3>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".demo").click(function () {
$("div").wrap("<section></section>");
});
});
</script>
Now, click on the Click Me button and observe that the div element is now surrounded by
the section element as shown in the below image.

Another Example For Better Understanding: In the below example, we have a


collection of 3 <div> elements. Wrap() method is implicitly iterating over the collection
i.e. iterating all the div elements in our example and wrapping all of them (i.e. all the div
elements) inside the section element.
<h3>jQuery Wrap Method</h3>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</br>
<button class="demo">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".demo").click(function () {
$("div").wrap("<section></section>");
});
});
</script>
Now, click on the Click Me button and observe that all the div elements are now wrapped
with the section element as shown in the below image.

Example: jQuery wrap method using the optional callback function


In the below example, we are using the callback function which is accepting index no of
the element currently iterating over as a parameter. We are wrapping the div elements in
a loop i.e. 1st div will be wrapped around <div class = “div0”></div> and 2 nd div element
will wrapped around <div class = “div1”></div> and so on….
<h1>jQuery Wrap Function</h1>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</br>
<button class="wrap">Click Me</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".wrap").click(function () {
$("div").wrap(function (index) {
return `<div class="div${index}"></div>`;
});
});
});
</script>
Now run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Elements tab and you can see the div elements are not assigned
with any class. Now, click on the Click Me button and again have a look at the div
elements. Now, the div elements are assigned with the class div0, div1, and so on as
shown in the below image.

jQuery Unwrap() method


The jQuery Unwrap method is used to remove the wrapper element from a specified
element i.e. it deletes the immediate parent of any specified element.
Syntax: $(selector).unwrap()
Example: jQuery Unwrap Method - Let us understand the jQuery unwrap method with
examples. In the below example; here we have a <p> tag which is descendant of
<section> element. Again, we have two button elements.
<h3>jQuery unwrap Method</h3>
<section>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</p>
</section>
</br>
<button class="demo wrap">Wrap</button>
<button class="demo unwrap">UnWrap</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".wrap").click(function () {
$("p").wrap("<div class='div1'></div>");
});
$(".unwrap").click(function () {
$("p").unwrap();
});
});
</script>
Now run the above code and open the browser developer tool. When we click on the wrap
button the <p> element is being wrapped by <div> which you can see in the elements
tab as shown in the below image.
Now when you click on the unwrap button, the immediate parent of the <p> element i.e.
<div> element will be removed and the section element becomes the immediate parent
of the p element which you can see in the Elements tab as shown in the below image.

Now <div> is removed and <section> is the immediate parent of the <p> element.
Again, click on the unwrap button, then the <section> element will also be removed
which you can see in the Elements tab as shown in the below image.
jQuery wrapAll() method:
The jQuery wrapAll() method wraps specified HTML element(s) around all selected
elements. The jQuery Wrap() method wraps specified HTML element(s) around each of
the selected elements but wrapAll() method does it around all selected elements.
Syntax: $(selector).wrapAll(element, function)
Example: jQuery wrapAll() method - Let us understand the jQuery wrapAll() method
with Examples. Please have a look at the below example.
<h3>jQuery WrapAll Method</h3>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</br>
<button class="demo wrap">WrapAll</button>
<button class="demo unwrap">Unwrap</button>
<button class="demo wrapall">WrapAll</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".wrap").click(function () {
$("div").wrap("<div class='div1'></div>");
});
$(".unwrap").click(function () {
$("div").unwrap();
});
$(".wrapall").click(function () {
$("div").wrapAll("<div class='div1'></div>");
});
});
</script>
Now run the above code and open the browser developer tool and have a look at the
Elements tab. When we click on the wrap button each of the div elements is wrapped
around an <div> of class ‘div1’.

Then when we click on the unwrap button all the selected <div> elements are
unwrapped as shown in the below image.
And again, when you click on the wrapAll button, you will see that all the selected <div>
elements will be wrapped under a single div of class ‘div1’ as shown in the below image.

jQuery wrapInner() Method


The wrapInner() method wraps specified HTML element(s) around the content
(innerHTML) of each selected element. In the case of previously discussed methods, they
are wrapping the whole elements. But the wrapInner method wraps the content of the
element instead of wrapping the whole element.
Syntax: $(selector).wrapInner(element, function)
Example: jQuery wrapInner() method - In the below example, we have 3 <div>
elements of class ‘div1’
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
}

.demo {
padding: 8px 20px;
border-radius: 30px;
font-size: 18px;
margin-top: 20px;
margin-right: 10px;
border: 1px solid black;
outline: none;
transition: 3ms;
}
.demo:hover {
background-color: #ddd;
cursor: pointer;
}
div,p {
display: block;
font-size: 20px;
margin: 35px;
padding: 35px;
}
.div1 {
background-color: rgb(120, 247, 247);
}
.div2 {
background-color: rgb(106, 243, 158);
}

</style>
<body>
<h1>jQuery Wrap Elements</h1>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<button class="demo wrap">WrapAll</button>
<button class="demo unwrap">Unwrap</button>
<button class="demo wrapInner">WrapInner</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".wrap").click(function () {
$("div").wrap("<div class='div2'></div>");
});
$(".unwrap").click(function () {
$("div").unwrap();
});
$(".wrapInner").click(function () {
$("div").wrapInner("<div class='div2'></div>");
});
});
</script>
We have 3 <div> elements of class ‘div1’

Now click on the ‘wrap’ button. You will see that all the <div> elements of class ‘div1’
will be wrapped by <div> of class ‘div2’
If we click on the ‘unwrap’ button then those will be unwrapped

Now click on the ‘wrapInner’ button. You will see that content of the <div> elements of
class ‘div1’ will be wrapped by <div> of class ‘div2’
jQuery Append and Prepend Elements
jQuery Append and Prepend Elements
If you have to insert a specified content at the end of any selected element(s), then
jQuery provides you a built-in method append(). Similarly, if you have to insert a specified
content at the starting of any selected element(s), then jQuery provides you a built-in
method prepend().
To append elements, jQuery provides
1. append()
2. appendTo()
To prepend elements, jQuery provides
1. prepend()
2. prependTo()
As these methods modify DOM elements, so they belong to the DOM manipulation
category.
jQuery append() Method
Syntax: $(selector).append(content, function(index, html))
Parameters:
Content: This is a required parameter. This specifies the content to insert (can contain
HTML tags)
Function: This is an optional callback function. It takes two optional parameters.
1. Index – returns the index position of the element in the set
2. HTML – Returns the current HTML of the selected element
Example: jQuery append method - Let us understand the jQuery append method with
examples. In the below example, we have a div element and inside that, we have some
content. By append() method, we are inserting a <h4> element at the end of the <div>.
<h3>jQuery Append Element</h3>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo append">Append</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".append").click(function () {
$("div").append("<h4>This is some content</h4>");
});
});
</script>
Now run the above code and you will see the following output in the browser.

Now click on the Append button. As soon as you click on the Append button, it will insert
an <h4> element at the end of the <div> and you will see the same as shown in the
below image.

You can verify the same in the browser developer tool. So, open the browser developer
tool by pressing the F12 key and have a look at the Elements tab and you can see the h4
element which is inserted by the jQuery Append method as shown in the below image.
Another Example For Better Understanding: We can also append an existing element
of the DOM to any specified element. If the content is an existing element, it will be
moved from its current position, and inserted at the end of the selected elements. For
better understanding please have a look at the below example.
In the below example, notice that the <h4> element is present in our DOM. When we
clicked on the Append button the <h4> element appended to the <div> element. Notice
that inside the append() method we have used a jQuery selector as a parameter.
<h3>jQuery Append Element</h3>
<h4>This is some content</h4>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo append">Append</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".append").click(function () {
$("div").append($("h4"));
});
});
</script>
Now run the application and you should see the following in the browser.
As soon as you click on the Append button, the existing h4 element moves from its
original position and append at the end of the div element which you can see in the below
image.
Example: jQuery Append Element using the callback function - Let us understand
this concept with an example. In the below example, we have two <div> elements
present in our DOM. The Append() method is iterating implicitly over them and
performing a function. Parameter index is receiving the current index no. of the <div>
and HTML is receiving previous HTML of the <div> element. The whole new content is
appended to each of the div.
<h3>jQuery Append Element using callback function</h3>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</div>
<div class="div2">
Maiores porro quibusdam deserunt id unde odit fugit libero.
</div>
</section>
</br>
<button class="demo append">Append</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".append").click(function () {
$("div").append(function (index, html) {
return `<h4>Previous Content of div indexed at ${index}:</h4> $
{html}`;
});
});
});
</script>
Now, run the above code and you should see the following output in the browser and also
have a look at the Elements tab of the browser developer tool.

Now click on the Append button and you should get the following output in the browser.

jQuery appendTo() Method


The jQuery append() method and appendTo() method have exactly the same functionality.
But the difference is in their syntax. The usage of these two is exactly the same.
Syntax: $(content).appendTo(selector)
Example: jQuery appendTo() method - Let us understand the jQuery AppendTo
method with examples. In the below example, we are appending a <h4> to only that
element having class div1.
<h3>jQuery AppendTo Method</h3>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</div>
<div class="div2">
Maiores porro quibusdam deserunt id unde odit fugit libero.
</div>
</section>
</br>
<button class="demo append">Append</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".append").click(function () {
$("<h4>This is some content</h4>").appendTo($(".div1"));
});
});
</script>
Now, run the above code and you should see the following output in the browser.

Now when you click on the Append button, it will add the h4 element to the div element
which having the class div1 as shown in the below image.
What is the difference between jQuery append and appendTo methods?
In jQuery, both of these methods perform the same task. As discussed, the only difference
between these two methods is in the syntax. With the jQuery append method, first, we
specify the target elements and then the content that we want to append, whereas we do
the opposite with the appendTo method.
jQuery Prepend() Method
Syntax: $(selector).prepend(content,function(index,html))
Parameters:
Content: This is a required parameter. This specifies the content to insert (can contain
HTML tags)
Function: This is an optional callback function. It takes two optional parameters.
1. Index: Returns the index position of the element in the set
2. Html: Returns the current HTML of the selected element
Example: jQuery Prepend Method - Let us understand the jQuery Prepend method
with some examples. In the below example, we have a div element and inside that, we
have some content. By the jQuery prepend() method, we are inserting a <h4> element at
starting of the <div> element.
<!DOCTYPE html>
<h3>jQuery Prepend Method</h1>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo prepend">Prepend</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".prepend").click(function () {
$("div").prepend("<h4>This is some content</h4>");
});
});
</script>
Now click on the Prepend button and you will see that the h4 element is inserted before
the div element as shown in the below image.

Another Example For Better Understanding: Now let’s see an example of an ordered
listing. In the below example, we have an ordered list.
<h3>jQuery Prepend Method</h3>
<section>
<div class="div1">
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
<li>List item 6</li>
</ol>
</div>
</section>
</br>
<button class="demo append">Append</button>
<button class="demo prepend">Prepend</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".append").click(function () {
$(".div1 ol").append("<li>Appended list item</li>");
});
$(".prepend").click(function () {
$(".div1 ol").prepend("<li>Prepnded list item</li>");
});
});
</script>
Now run the above code and then click on the append button. Once you click on the
Append button a new list item is added. Notice that the order of the appended item is 7.

Now click on the Prepend button. Once you click on the Prepend button a new list item is
added. Notice that the order of the new item is 1 i.e. new list item is added at the top of
the list.
Look that the order number is maintained.
jQuery prependTo() Method
The jQuery prepend() method and prependTo() method have exactly the same
functionality. But the difference is in their syntax. The usage of these two is exactly the
same.
Syntax: $(content).prependTo(selector)
What is the difference between jQuery prepend and prependTo methods?
In jQuery, both of these methods perform the same task. As discussed, the only difference
between these two methods is in the syntax. With the jQuery prepend method, first, we
specify the target elements and then the content that we want to prepend, whereas we
do the opposite with the prependTo method.
Example: appendTo() and prependTo() method - Let us understand the jQuery
prependTo method with an example. In the below example, we are using appendTo() and
prependTo() to add table rows at the end and at the top respectively.
<h3>jQuery PrependTo and AppendTo Method</h3>
<table id="code">
<thead>
<tr>
<th>Front End</th>
<th>Back End</th>
<th>Data Base</th>
</tr>
</thead>
<tbody>
<td>jQuery</td>
<td>PHP</td>
<td>mySQL</td>
</tr>
<tr>
<td>ReactJS</td>
<td>Node JS</td>
<td>MongoDB</td>
</tr>
<tr>
<td>Angular</td>
<td>Express JS</td>
<td>PostgreSQL</td>
</tr>
</tbody>
</table>
</br>
<button class="demo append">Append</button>
<button class="demo prepend">Prepend</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".append").click(function () {

$('<tr><td>VueJS</td><td>Java</td><td>Redis</td></tr>').appendTo("#code
tbody");
});
$(".prepend").click(function () {

$('<tr><td>Bootstrap</td><td>Ruby</td><td>Cassandra</td></tr>').prependTo("#
code tbody");
});
});
</script>
Now run the above code and you will get the following output.

Now click on the Append button. Once you click on the Append button, it will add a new
table row at the end of the table body as shown in the below image.
Now, click on the Prepend button. Once you click on the Prepend button, it will add a
new table row at the top of the table body as shown in the below image.

Difference between jQuery prepend and append Methods?


The jQuery prepend method, inserts the specified content to the beginning of each
element in the set of matched elements, whereas the jQuery append method inserts the
specified content to the end of each element in the set of matched elements.
jQuery Insert Elements Before and After
jQuery Insert Elements Before and After Certain Elements
If you have to insert a specified content before any selected element(s), then jQuery
provides you a built-in method before(). Similarly, if you have to insert a specified content
after any selected element(s), then jQuery has a method after(). This sounds similar
to append() & prepend() which we have learned in the previous article. But there is a
huge difference.
append() vs .after()
1. .append(): Insert content, specified by the parameter, to the end of each element in
the set of matched elements.
2. .after(): Insert content, specified by the parameter, after each element in the set of
matched elements.
prepend() vs .before()
1. prepend(): Insert content, specified by the parameter, to the beginning of each
element in the set of matched elements.
2. .before(): Insert content, specified by the parameter, before each element in the set
of matched elements.
So, append and prepend refers to the child of the object whereas after and before refers
to the sibling of the object.
jQuery before() Method
Syntax: $(selector).before(content, function(index))
Parameters:
Content: This is a required parameter. This specifies the content to insert (can contain
HTML tags)
Function: This is an optional callback function. It takes an optional parameter
1. index – Returns the index position of the element in the set
Example: jQuery before() Method - In the below example, we have a div and inside
that some content. By before() method, we are inserting a <h2> element before the
<div> element.
<h3>jQuery Before and After</h3>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo before">Before</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".before").click(function () {
$("div").before("<h2>This is title of the div</h2>");
});
});
</script>
Now, run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Elements tab as shown in the below image.

Now, click on the Before button and have a look at the elements tab as well as browser,
you will see that h2 element is added before the div element as shown in the below
image.
Example: jQuery Before Method - We can also insert an existing element of the DOM
before any specified element. If the content is an existing element, it will be moved from
its current position, and inserted before the selected elements.
<h3>jQuery Before and After</h3>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
<h2>This is title of the div</h2>
</br>
<button class="demo before">Before</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".before").click(function () {
$("div").before($("h2"));
});
});
</script>
Now, run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Elements tab as shown in the below image. Notice that the <h2>
element is present in our DOM after the <section> element.
Now, click on the Before button, and observe that the <h2> was inserted before <div>
element. Notice that inside the before() method we have used a jQuery selector as a
parameter.
Example: jQuery Before Method Using the callback function - In the below
example, we have two <div> elements present in our DOM. before() method is iterating
implicitly over them and performing a function. Parameter index is receiving the current
index no. of the <div>. The new content is inserted before each of the div.
<h3>jQuery Before and After</h3>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</div>
<div class="div2">
Maiores porro quibusdam deserunt id unde odit fugit libero.
</div>
</section>
</br>
<button class="demo before">Before</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".before").click(function () {
$("div").before(function (index) {
return `<h2>This is the title of div indexed at ${index}:</h2>`;
});
});
});
</script>
Now, run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Elements tab as shown in the below image.
Now, click on the Before button, and observe that the <h2> was inserted before each
<div> element as shown in the below image.
jQuery insertBefore() Method
The .before() and .insertBefore() methods perform the same task. The major difference is
in the syntax specifically, in the placement of the content and target. With .before(), the
content to be inserted comes from the method’s argument: $
(target).before(contentToBeInserted). With .insertBefore(), on the other hand, the
content precedes the method and is inserted before the target, which in turn is passed as
the .insertBefore() method’s argument: $(contentToBeInserted).insertBefore(target)
Syntax: $(content).insertBefore(selector)
Example: jQuery insertBefore() Method
In the below example, we are inserting a <h2> element before only that <div> having
class ‘div2’
<!DOCTYPE html>
<html>
<head>
<title>jQuery Before and After</title>
</head>
<body>
<h3>jQuery InsertBefore Method</h3>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</div>
<div class="div2">
Maiores porro quibusdam deserunt id unde odit fugit libero.
</div>
</section>
</br>
<button class="demo before">Before</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".before").click(function () {
$("<h2>This is a title</h2>").insertBefore("div.div2");
});
});
</script>
</body>
</html>
Now, run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Elements tab as shown in the below image. Here, you can see, we
have two div elements. The first div element is having class div1 and the second div
element is having class div2.
Now, click on the Before button, and observe that the <h2> was inserted before the
<div> element having class div2 as shown in the below image.

jQuery after() method


Syntax: $(selector).after(content,function(index))
Parameters:
Content: This is a required parameter. This specifies the content to insert (can contain
HTML tags)
Function: This is an optional callback function. It takes an optional parameter.
1. index – Returns the index position of the element in the set
Example: jQuery after() method
In the below example, we have a div and inside that some content. By after() method, we
are inserting a <h2> element after the <div>
<h3>jQuery Before & After</h3>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo after">After</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".after").click(function () {
$("div").after("<h2>This is a Title</h2>");
});
});
</script>
Now, run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Elements tab as shown in the below image.

Now, click on the After button, and observe that the <h2> was inserted after the <div>
element as shown in the below image.
Note: We can use the callback exactly the same as the before() method. This is a task for
you. Please do the same task and give your code in the comment section.
jQuery insertAfter() method
The .after() and .insertAfter() methods perform the same task. The major difference is in
the syntax—specifically, in the placement of the content and target. With .after(), the
content to be inserted comes from the method’s argument: $
(target).after(contentToBeInserted). With .insertAfter(), on the other hand, the content
precedes the method and is inserted after the target, which in turn is passed as
the .insertAfter() method’s argument: $(contentToBeInserted).insertAfter(target).
Syntax: $(content).insertAfter(selector)
Example: jQuery insertAfter() method
In the below example, we are using insertAfter() to insert content after each of the
selected <div>
<h1>jQuery Insert After</h1>
<section>
<div class="div1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="div2">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo after">After</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".after").click(function () {
$("<h2>This is a Title</h2>").insertAfter("div");
});
});
</script>
Now, run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Elements tab as shown in the below image.
To insert an element before another element
1. Before
2. insertBefore
To insert an element after another element
1. after
2. inserAfter
As these methods modify DOM, they belong to the DOM manipulation category.
jQuery Add, Remove and Toggle class
jQuery Add, Remove, and Toggle class
jQuery provides several methods, such as addClass(), removeClass(), toggleClass(), etc.
to manipulate the CSS classes assigned to HTML elements.
jQuery addClass() Method: If you want to add one or more classes to the class
attribute of any element. Then jQuery has the method called addClass(). It adds one or
more classes to one or more elements simultaneously.
Syntax: $(selector).addClass(classname, function(index, currentclass))
Parameters:
Classname: Required. Specifies one or more class names to be added
Function: Optional. Specifies a function that returns one or more class names to be
added. It takes two parameters.
1. index – Returns the index position of the element in the set
2. currentclass – Returns the current class name of the selected element
Example: jQuery addClass() Method - In the below example, div1 class is added to
every <div> element which is selected when we click on the Add Class button.
<section>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo addclass">Add Class</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".addclass").click(function () {
$("div").addClass("div1");
});
});
</script>
Now, run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Elements tab and you can see the div elements without having any
classes as shown in the below image.
Adding Multiple Classes using jQuery AddClass Method
To add multiple classes, you can separate the classes by space or you can pass an array
of class names.
$(selector).addClass(classname1 classname2) or,
$(selector).addClass([classname1, classname2,…………..])
In the below example, we are adding multiple classes to the div elements.
<h3>jQuery Add and Remove Class</h3>
<section>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo addclass">Add Class</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".addclass").click(function () {
$("div").addClass("bgcolor font border shadow");
// $("div").addClass(["bgcolor", "font", "border", "shadow"]);
(You can pass an array)
});
});
</script>
jQuery AddClass Method Using the callback function - In the below example, the
addClass() method is performed by a callback function. Index parameter is receiving the
index of the current <div> and currentClass parameter is receiving the present class in
the <div>. In this case, test class is present in the <div> element. New classes test0 and
test1 are being added to the div elements respectively.
<h3>jQuery Add and Remove Classes</h3>
<section>
<div class="test">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="test">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo addclass">Add Class</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".addclass").click(function () {
$("div").addClass(function (index, currentClass) {
return currentClass + index;
});
});
});
</script>
Now, click on the Add Class button, and observe that test0 is added to the first div
element and test1 is added to the second div element as shown in the below image.
jQuery removeClass() method
If you want to remove one or more classes from the class attribute of any element. Then
jQuery has the method called removeClass. It removes one or more classes from one or
more elements simultaneously.
Syntax: $(selector).removeClass(classname, function(index, currentclass))
Parameters:
Classname: Required. Specifies one or more class names to be removed
Function: Optional. Specifies a function that returns one or more class names to be
removed. It takes two parameters.
1. index – Returns the index position of the element in the set
2. currentclass – Returns the current class name of the selected element
Note: If you don’t pass any parameter to removeClass() then it will remove all the classes
attached to a specific element.
Example: jQuery removeClass() method - In the below example, notice that we can
remove a multiple class from an element (for that we can pass an array also). Or simply if
we don’t pass any parameter to the method then it is going to remove all the classes.
<title>jQuery Add and Remove Class</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
}

section {
background-color: #d1cfcf;
width: 80%;
height: auto;
padding: 10px;
font-size: 20px;
font-weight: 200;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
margin-bottom: 20px;
}
.demo {
padding: 8px 20px;
border-radius: 30px;
font-size: 18px;
margin-top: 20px;
margin-right: 10px;
border: 1px solid black;
outline: none;
transition: 3ms;
}
.demo:hover {
background-color: #ddd;
cursor: pointer;
}
div {
display: block;
font-size: 20px;
margin: 35px;
padding: 35px;
}

.bgcolor {
background-color: rgb(120, 247, 215);
}
.font {
font-style: italic;
font-weight: 700;
}
.border {
border: 2px solid black;
border-radius: 20px;
}
.shadow {
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
}
</style>
</head>

<body>
<h3>jQuery Add and Remove Classes</h3>
<section>
<div class="bgcolor font border shadow">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
<button id="remove2" class="demo">Remove Only Border & Shadow</button>
<button id="removeall" class="demo">Remove All Classes</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#remove2").click(function () {
$("div").removeClass("border shadow");
});
$("#removeall").click(function () {
$("div").removeClass();
});
});
</script>
Now, run the above code and you will see the following output in the browser.

Now, click on the ‘Remove only border & shadow’ button and you can see it will remove
the border and shadow class and you will get the following output in the browser.
Now, click on the ‘Remove all classes’ button which will remove all the classes and you
will get the following output in the browser.

Example: Remove classes Using the callback function


In the below example, we are removing the ‘test’ class from the div elements if they are
indexed at 0 or 3.
<h1>jQuery Add and Remove Classes</h1>
<section>
<div class="test">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="test">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="test">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="test">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
</br>
<button class="demo removeclass">Remove Class</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".removeclass").click(function () {
$("div").removeClass(function (index) {
if (index == 0 || index == 3) {
return "test";
} else {
return "";
}
});
});
});
</script>
Now, run the above code and you will see the following output in the browser. As you can
see in the below image, the class test is applied to all four div elements.

Now, click on the ‘Remove classes’ button which will remove the test class from the first
and fourth div (index 0 and 3) elements and you will get the following output in the
browser.
jQuery toggleClass() Method
The toggleClass() method toggles between adding and removing one or more class names
from the selected elements. This method adds a class is that is not present and removes
the class if that is already present. However, by using the “switch” parameter, you can
specify to only remove, or only add a class name.
Syntax: $(selector).toggleClass(classname, function(index, currentclass), switch)
Parameters:
Classname: Required. This is the class name(s) you want to add or remove
Switch: Optional. A Boolean value specifying if the class should only be added (true), or
only be removed (false).
Function: Optional. Specifies a function that returns one or more class names that you
want to add/remove. It takes two parameters as follows:
1. index – Returns the index position of the element in the set
2. currentclass – Returns the current class name of selected elements
Example: jQuery toggleClass() Method - In the below example, we are using the
callback function to toggle between the corresponding classes. Here the class we want to
toggle is ‘test’ followed by the index. For example, for 1 st div, if class .test0 is present
then that will be removed and if that is not present then it is going to be added.
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
}

section {
background-color: #d1cfcf;
width: 80%;
height: auto;
padding: 10px;
font-size: 20px;
font-weight: 200;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
margin-bottom: 20px;
}
.demo {
padding: 8px 20px;
border-radius: 30px;
font-size: 18px;
margin-top: 20px;
margin-right: 10px;
border: 1px solid black;
outline: none;
transition: 3ms;
}
.demo:hover {
background-color: #ddd;
cursor: pointer;
}
div {
display: block;
font-size: 20px;
margin: 35px;
padding: 35px;
}

.test0,
.test2 {
background-color: rgb(120, 247, 215);
font-style: italic;
font-weight: 700;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
border: 2px solid black;
border-radius: 20px;
}
.test1,
.test3 {
background-color: rgb(255, 219, 102);
font-style: italic;
font-weight: 700;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
border: 2px solid black;
border-radius: 20px;
}
</style>
<h1>jQuery Add and Remove Classes</h1>
<section>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
<button class="demo toggleclass">Toggle Class</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".toggleclass").click(function () {
$("div").toggleClass(function (index) {
return "test" + index;
});
});
});
</script>
Now, run the above code and you will see the following output in the browser.
Now click on the Toggle Class button and you should get the following output in the
browser.

jQuery hasClass() Method:


The jQuery hasClass() Method determines that whether a specified class is present in an
element or not.
It returns a Boolean value.
Syntax: $(selector).hasClass(classname)
Example: In the below example, for every div element, we are checking for the specified
class and then log the same in the Console.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Add and Remove Class</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
}
section {
background-color: #d1cfcf;
width: 80%;
height: auto;
padding: 10px;
font-size: 20px;
font-weight: 200;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
margin-bottom: 20px;
margin: auto;
}
.demo {
padding: 8px 20px;
border-radius: 30px;
font-size: 18px;
margin-top: 20px;
margin-right: 10px;
border: 1px solid black;
outline: none;
transition: 3ms;
}
.demo:hover {
background-color: #ddd;
cursor: pointer;
}
div {
display: block;
font-size: 20px;
margin: 35px;
padding: 35px;
}
.bgcolor {
background-color: rgb(120, 247, 215);
}
.font {
font-style: italic;
font-weight: 700;
}
.shadow {
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
}
.border {
border: 2px solid black;
border-radius: 20px;
}
</style>
</head>
<body>
<h1>jQuery Add and Remove Classes</h1>
<section>
<div class="bgcolor font shadow border">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="bgcolor font shadow">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="bgcolor font">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
<div class="bgcolor">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
veritatis ab fugiat ducimus, totam ratione quod
</div>
</section>
<button class="demo hasClass">Has Class</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".hasClass").click(function () {
$("div").each(function (index) {
console.log(
`The div at ${index} has bgcolor class : ${$(this).hasClass(
"bgcolor"
)}`
);
console.log(
`The div at ${index} has font class : ${$
(this).hasClass("font")}`
);
console.log(
`The div at ${index} has shadow class : ${$(this).hasClass(
"shadow"
)}`
);
console.log(
`The div at ${index} has border class : ${$(this).hasClass(
"border"
)}`
);
});
});
});
</script>
</body>
</html>
Now run the above code. Open the browser develop tool by pressing the F12 Key and
select the Console tab. Then click on the Has Class button and you should see the
following logs in the Console tab.

Points to Remember:
1. addClass: It is used to add one or more specified classes. To add multiple classes, we
need to separate them with a “space”.
2. removeClass: It is used to remove one or multiple or all classes. In order to remove
multiple classes, we need to separate them with a “space” whereas to remove all
classes, we don’t need to specify any class name.
3. toggleClass: It is used to Toggle one or more specified classes. If the element has the
specified class, then it is removed, if the class is not present then it is added.
4. hasClass: It is used to return true if an element has the specified class otherwise
false.
jQuery Map Method
jQuery Map Method
1. We have learned jquery each() method in the previous articles. Now there is another
method in jquery called the map() method. jQuery map() method is also used to iterate
over the matched elements.
2. In brief, if you want to produce a plain array or concatenated string based on the set
of matched elements use the map() method over each() method.
3. The map() method passes each element in the current matched set through a function,
producing a new jQuery object containing the return values.
4. As the return value is a jQuery object, which contains an array, it’s very common to
call get() on the result to work with a basic array.
Syntax: $(selector).map( function(index, currentElement){})
Parameters of the callback:
1. Index: index of the current DOM element which we are iterating over
2. currentElement: Current DOM element of the iteration.
Example: jQuery Map Method - Suppose that we have to make an array based on the
index and values of a list item. At first, let’s see how to do this by each() method. In the
below example, we are using each() method. We have created an empty array first. Then
for each iteration, we are pushing a new item to that array. Here item parameter is
receiving the current element over which the iteration is going on; so we can use $(this)
too. In that case, we can get rid of the item parameter.
<h3>jQuery Map Method</h3>
<section>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>jQuery</li>
<li>ReactJS</li>
<li>Angular</li>
</ul>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
const items = [];
$("li").each(function (index, item) {
items.push(`Index: ${index} | Text: ${$(item).text()}`);
});
console.log(items);
});
</script>
Now let’s see how to do this by using the jQuery map() method.
In this example, we are using the map method. Map() method itself returns a jQuery
object from which we can get a plain array by get() method. So there is no need to
initiate with an empty array. Map() method is simpler to use here.
<h3>jQuery Map Method</h3>
<section>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>jQuery</li>
<li>ReactJS</li>
<li>Angular</li>
</ul>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
const items = $("li")
.map(function (index, item) {
return `Index: ${index} | Text: ${$(item).text()}`;
})
.get();
console.log(items);
});
</script>
jQuery Map Method Example: Now suppose in the same DOM, we have to create a
concatenated string with values of list items delimited by “;”. At first, let’s see by each()
method. In the below example, we have initiated an empty string. For each iteration, we
are adding the value to the string followed by a “;”
<h3>jQuery Each Method</h3>
<section>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>jQuery</li>
<li>ReactJS</li>
<li>Angular</li>
</ul>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let string = "";
$("li").each(function (index, item) {
string += $(item).text() + ";";
});
console.log(string);
});
</script>
You can see here, in this method, there is an “;” at the end of the string as we were
adding a “;” at the end of the list text. We don’t want that. We can use substr() method to
get a substring from that as shown in the below example. In the below example, we are
extracting a substring starting from index 0 to the second last character of the string.
<h3>jQuery Each Method</h3>
<section>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>jQuery</li>
<li>ReactJS</li>
<li>Angular</li>
</ul>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let string = "";
$("li").each(function (index, item) {
string += $(item).text() + ";";
});
string = string.substr(0, string.length - 1);
console.log(string);
});
</script>
Now run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Console tab and you should see the following logs.
Now let’s see how to achieve the same by using the jQuery map() method. We know that
the map() method returns a jQuery object containing an array. So by get() method we are
converting that into a plain array and then by JavaScript join() method we are joining the
values of the array with the separator “;”.
<h3>jQuery Map Method</h3>
<section>
<ul>
<li>HTML5</li>
<li>CSS3</li>
<li>jQuery</li>
<li>ReactJS</li>
<li>Angular</li>
</ul>
</section>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let string = $("li")
.map(function (index, item) {
return $(item).text();
})
.get()
.join(";");
console.log(string);
});
</script>
Now run the above code and open the browser developer tool by pressing the F12 key
and have a look at the Console tab and you should see the following logs.
Another Example of jQuery Map Method: Let’s see another example of the jQuery
map() method. In the below example, we have a form. At the click of the submit button,
we are alerting the values of the input fields as a string by using the map() method.
<section>
<form action="/">
<fieldset>
<legend>Name:</legend>
<input
type="text"
name="Name"
placeholder="Enetr Your Name"
value="John doe"
/>
</fieldset>
<fieldset>
<legend>Email:</legend>
<input
type="email"
name="Email"
placeholder="Enetr Your Email"
value="johndoe@gmail.com"
/>
</fieldset>
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position" multiple>
<option value="webDeveloper" selected>Web Developer</option>
<option value="webDesigner">Web Designer</option>
<option value="graphicDesigner">Graphic Designer</option>
<option value="businessAnalyst">Business Analyst</option>
<option value="telecaller">Telecaller Executive</option>
</select>
</fieldset>
</fieldset>
</br>
<button class="demo" type="submit">Submit</button>
</form>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
var values = $(":input")
.map(function (index, item) {
return $(item).val();
})
.get()
.join("-");
var values = values.substr(0, values.length - 1);
$(".demo").click(function () {
alert(values);
});
});
</script>
Now run the above code and click on the Submit button and you will get the following
output.

Difference Between jQuery Each and Map Method


Difference Between jQuery Each and Map Method
We had a comparative study of the map() and each() method in our previous articles.
Now in this article, we will study about the differences between $.each() and $.map() in
jQuery. The each() method is meant to be an immutable iterator, whereas the map()
method can be used as an iterator, but is really meant to manipulate the supplied array
and return a new array. The differences between these two functions are as follows.
Syntax of each function: $.each( function(index, element){})
Syntax of map function: $.map( function(element, index){})
Notice that, both functions are taking a callback function but the order of the parameters
of the callback is different. In each function, the first parameter of the callback is the
index of the current element and the second parameter is the current element of the
collection. But this is reverse for map function. In the map function, the first parameter of
the callback is the current element of the collection and the second parameter is the
index of the current element. Let’s see an example to prove that.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = [10, 20, 30, 40, 50];
$.each(arr, function (index, element) {
console.log(`Index : ${index} Element : ${element}`);
});
});
</script>
Now let’s see for map function.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = [10, 20, 30, 40, 50];
$.map(arr, function (element, index) {
console.log(`Index : ${index} Element : ${element}`);
});
});
</script>
Now run the above code and open the browser developer tool and have a look at the
Console tab. Notice that the order of the parameters is different here. Here 2 nd parameter
is representing the index and the 1st parameter is the value of the current element.
Here comes a question. What if we put the parameters in the ‘index, element’ order?
Let’s see
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = [10, 20, 30, 40, 50];
$.map(arr, function (index, element) {
console.log(`Index : ${index} Element : ${element}`);
});
});
</script>
The answer is clear now. Here whatever may be the name of the 1 st parameter that is
always receiving the current element of the array, and on the other hand, the
2nd parameter is receiving the index irrespective of the name of the parameter as shown
in the below image.
Return Value in jQuery Each and Map Method: jQuery each() function is used to
perform certain actions on an array by a callback function. It returns the original array
and doesn’t change it. On the other hand map() function operates the callback function
on the given collection and returns a new array. Let’s understand this difference by an
example
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = [1, 2, 3, 4, 5];
console.log(
$.each(arr, function (index, element) {
return element * element;
})
);
});
</script>
Notice that we are using each function here. But when we are trying to log the return
value then it can be seen that it is only the original array that is returning.

Now, look at the map() function.


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = [1, 2, 3, 4, 5];
console.log(
$.map(arr, function (element, index) {
return element * element;
})
);
});
</script>
The jQuery Map() function performs the operation on each element of the array and is
storing those into a new array. In the console, we are getting the new array in which the
elements are the square of the elements of the original array.

this keyword in jQuery Each and Map Method: We know that the ‘this’ keyword
refers to the current element or object, over which the iteration is currently going on. But
the behavior of the ‘this’ keyword is different for the each() & map() function. Let’s
understand these by an example. Look at each function first.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = ["tiger", 20, 30, true, 50];
$.each(arr, function () {
console.log(this);
});
});
</script>
Here for every iteration, we are trying to print the current element of the collection on
the console by calling the ‘this’ keyword.
Notice that we are getting the current element for every iteration in the console. Now for
the map function behavior of the ‘this’ keyword has changed.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = ["tiger", 20, 30, true, 50];
$.map(arr, function () {
console.log(this);
});
});
</script>
Here ‘this’ keyword is not referring to the current element. Here ‘this’ is just referring to
the window object.

Terminating the iteration in jQuery Each and Map Method: We have a way to
terminate the iteration in each() function. But there is no way to terminate the iteration
in the map() method. Let’s see by example.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = [10, 20, 30, 40, 50];
$.each(arr, function (index, element) {
if (element == 30) {
return false;
}
console.log(`Index : ${index} Element : ${element}`);
});
});
</script>
We use return false; at any stage of the iteration to break the loop. Here we are telling
our program that if the current element equal to 30 then the loop should be broken and
iteration should not be executed for the rest of the elements. Notice that in the console
we are getting the only result of the first two iterations.

Now, look at the map method.


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = [10, 20, 30, 40, 50];
$.map(arr, function (element, index) {
if (element == 30) {
return false;
}
console.log(`Index : ${index} Element : ${element}`);
});
});
</script>
Here we are using the return false; in the same way but the behavior is different here.
So here what is happening? When the iteration reaches the if the block at (element ==
30) and checks the condition is true, it is returning false, but the iteration doesn’t stop.
That one element is not returned but the loop continues and for the rest two elements the
code is executing and performing the function. So, we are getting all elements except 30.
In this way, we can remove an element from a collection while using the map function.

Performance in jQuery Each and Map Method: Let’s take a look at which method
takes more time.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
let arr = [10, 20, 30, 40, 50];
var startEach = performance.now();
$.each(arr, function (index, element) {
console.log(index + element * 10000000000);
});
var endEach = performance.now();
console.warn(`Time taken by each() : ${endEach - startEach} ms`);

var startMap = performance.now();


$.map(arr, function (element, index) {
console.log(index + element * 10000000000);
});
var endMap = performance.now();
console.warn(`Time taken by map() : ${endMap - startMap} ms`);
});
</script>
We are measuring the time taken by the function to call by JavaScript performance.now()
method.

You can see that there is a little difference in the performance time of the two functions.
But that is not conclusive that may change for different parameters.
So, we can conclude that each and map function is based on your use case. If you want to
create a new array that can be used for further methods like reduce(), filter() then you
should go for the map function. If you only wish to perform any action to the elements of
your collection then opt for each method.
Form Events
A form event is fired when a form control receive or loses focus or when the user modify
a form control value such as by typing text in a text input, select any option in a select
box etc. Here're some commonly used jQuery methods to handle the form events.
The change() Method - The jQuery change() method attach an event handler function
to the <input>, <textarea> and <select> elements that is executed when its value
changes. The following example will display an alert message when you select any option
in dropdown select box.
<script>
$(document).ready(function(){
$("select").change(function(){
var selectedOption = $(this).find(":selected").val();
alert("You have selected - " + selectedOption);
});
});
</script>
Note: For select boxes, checkboxes, and radio buttons, the event is fired immediately
when the user makes a selection with the mouse, but for the text input and textarea the
event is fired after the element loses focus.
The focus() Method - The jQuery focus() method attach an event handler function to
the selected elements (typically form controls and links) that is executed when it gains
focus. The following example will display a message when the text input receive focus.
<script>
$(document).ready(function(){
$("input").focus(function(){
$(this).next("span").show().fadeOut("slow");
});
});
</script>
The blur() Method - The jQuery blur() method attach an event handler function to the
form elements such as <input>, <textarea>, <select> that is executed when it loses
focus. The following example will display a message when the text input loses focus.
<script>
$(document).ready(function(){
$("input").blur(function(){
$(this).next("span").show().fadeOut("slow");
});
});
</script>
The submit() Method - The jQuery submit() method attach an event handler function to
the <form> elements that is executed when the user is attempting to submit a form. The
following example will display a message depending on the value entered when you try to
submit the form.
<script>
$(document).ready(function(){
$("form").submit(function(event){
var regex = /^[a-zA-Z]+$/;
var currentValue = $("#firstName").val();
if(regex.test(currentValue) == false){
$("#result").html('<p class="error">Not
valid!</p>').show().fadeOut(1000);
// Preventing form submission
event.preventDefault();
}
});
});
</script>
Tip: A form can be submitted either by clicking a submit button, or by pressing Enter
when certain form elements have focus.
Document/Window Events
Events are also triggered in a situation when the page DOM (Document Object Model) is
ready or when the user resize or scrolls the browser window, etc. Here're some
commonly used jQuery methods to handle such kind of events.
The ready() Method - The jQuery ready() method specify a function to execute when
the DOM is fully loaded.
The following example will replace the paragraphs text as soon as the DOM hierarchy has
been fully constructed and ready to be manipulated.
<script>
$(document).ready(function(){
$("p").text("The DOM is now loaded and can be manipulated.");
});
</script>
The resize() Method - The jQuery resize() method attach an event handler function to
the window element that is executed when the size of the browser window changes.
The following example will display the current width and height of the browser window
when you try to resize it by dragging its corners.
<script>
$(document).ready(function(){
$(window).resize(function() {
$(window).bind("resize", function(){
$("p").text("Window width: " + $(window).width() + ", " +
"Window height: " + $(window).height());
});
});
});
</script>
The scroll() Method - The jQuery scroll() method attach an event handler function to
the window or scrollable iframes and elements that is executed whenever the element's
scroll position changes.
The following example will display a message when you scroll the browser window.
<script>
$(document).ready(function(){
$(window).scroll(function() {
$("p").show().fadeOut("slow");
});
});
</script>
jQuery Change Event
jQuery Change Event
If you want to trigger any change in your input fields and want to perform any task when
the input field changes then jQuery has a method called 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.
1. For select menus, the change event occurs when an option is selected.
2. For text fields or text areas, the change event occurs when the field loses focus after
the content has been changed.
3. For radio and checkboxes, the change event occurs when any of the radio or checkbox
is selected.
Syntax:

Parameters:
Function: Specifies the function to run when the change event occurs for the selected
elements. When you want to manually trigger the change event you can use the following
syntax
$(selector).change()
Example: jQuery Change Event
We will see an example of a select element first.
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
section {
background-color: #d1cfcf;
width: 80%;
height: auto;
padding: 10px;
font-size: 20px;
font-weight: 200;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
margin-bottom: 20px;
margin: auto;
}
.demo {
display: block;
padding: 8px 20px;
border-radius: 30px;
font-size: 18px;
margin-top: 20px;
margin-right: 10px;
border: 1px solid black;
outline: none;
transition: 3ms;
}
.demo:hover {
background-color: #ddd;
cursor: pointer;
}
fieldset {
padding: 15px;
margin: 10px;
font-size: 16px;
}
select option {
margin: 5px;
}
select {
padding: 5px;
width: 250px;
margin-left: 5px;
font-size: 14px;
height: auto;
}
</style>
<section>
<form action="/">
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position">
<option value="webDeveloper">Web Developer</option>
<option value="webDesigner">Web Designer</option>
<option value="graphicDesigner">Graphic Designer</option>
<option value="businessAnalyst">Business Analyst</option>
<option value="telecaller">Telecaller Executive</option>
</select>
</form>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".position").change(function () {
alert($(this).val());
});
});
</script>
Notice that whenever you select any of the options from the drop-down list, then that
option value will be alerted as shown in the below image.
Let’s see when there are multiple attributes are present. In the below example, for each
selected option we are appending the option value whenever any option gets selected to
the empty string and showing that in the result div.
<section>
<form action="/">
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position" multiple>
<option value="webDeveloper">Web Developer</option>
<option value="webDesigner">Web Designer</option>
<option value="graphicDesigner">Graphic Designer</option>
<option value="businessAnalyst">Business Analyst</option>
<option value="telecaller">Telecaller Executive</option>
</select>
<div class="result"></div>
</form>
</section>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$( "div.result" ).text( str );
})
});
</script>
Now run the above code and select multiple options as shown in the below image.
Example: Now let’s see for the <input> elements. In the below example, we are
targeting all input elements which are triggering the change event. You type something
on the name or email field and when you will lose focus from those you will see the value
in the alert. Similarly, for the radio and checkboxes, as soon as you check any option, the
value will be alerted
<section>
<form action="/">
<fieldset>
<legend>Name:</legend>
<input type="text" name="Name" placeholder="Enter Your Name" />
</fieldset>
<fieldset>
<legend>Email:</legend>
<input type="email" name="Email" placeholder="Enter Your Email" />
</fieldset>
<fieldset>
<legend>Skillset:</legend>
<label for="HTML">HTML5</label>
<input type="checkbox" name="skillset" value="HTML" />
<label for="CSS">CSS3</label>
<input type="checkbox" name="skillset" value="CSS" />
<label for="JavaScript">JavaScript</label>
<input type="checkbox" name="skillset" value="JavaScript" />
<label for="jquery">jQuery</label>
<input type="checkbox" name="skillset" value="jquery" />
</fieldset>

<fieldset>
<legend>Select Your Gender</legend>
<label
>Male: <input type="radio" name="radiogroup" value="Male"
/></label>
<label
>Female: <input type="radio" name="radiogroup" value="Female"
/></label>
</fieldset>
<div class="result"></div>
</form>
</section>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("input").change(function () {
value = $(this).val();
alert(value);
});
});
</script>
jQuery Change Event Real-Time Example: Now let’s have a look at an example,
where all input selects and textarea will be present. In the below example, we are
targeting all input fields by “:input” selector. We know that :input is going to target all
the input fields including select and textarea. We are triggering the change on the input
fields and getting the values whenever the inputs are changing and are appending the
result to the div result
<section>
<form action="/">
<fieldset>
<legend>Name:</legend>
<input type="text" name="Name" placeholder="Enter Your Name" />
</fieldset>
<fieldset>
<legend>Email:</legend>
<input type="email" name="Email" placeholder="Enter Your Email" />
</fieldset>
<fieldset>
<legend>Skillset:</legend>
<label for="HTML">HTML5</label>
<input type="checkbox" name="skillset" value="HTML" />
<label for="CSS">CSS3</label>
<input type="checkbox" name="skillset" value="CSS" />
<label for="JavaScript">JavaScript</label>
<input type="checkbox" name="skillset" value="JavaScript" />
<label for="jquery">jQuery</label>
<input type="checkbox" name="skillset" value="jquery" />
</fieldset>

<fieldset>
<legend>Select Your Gender</legend>
<label
>Male: <input type="radio" name="radiogroup" value="Male"
/></label>
<label
>Female: <input type="radio" name="radiogroup" value="Female"
/></label>
</fieldset>
<fieldset>
<legend>Select the position you want to apply</legend>
<select name="position" class="position" multiple>
<option value="webDeveloper">Web Developer</option>
<option value="webDesigner">Web Designer</option>
<option value="graphicDesigner">Graphic Designer</option>
<option value="businessAnalyst">Business Analyst</option>
<option value="telecaller">Telecaller Executive</option>
</select>

<fieldset>
<legend>Any other comments</legend>
<textarea name="textarea" rows="3" cols="20"></textarea>
</fieldset>
<div class="result"></div>
</form>
</section>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
var values= "";
$(":input").change(function () {
if (values == ""){
values = $(this).val();
}
else{
values +=" ,"+ $(this).val();
}
$('.result').html(values);
})
});

</script>
Now run the above code and fill-up the form with input values and check box values.
Immediately you will see the selected and input values as shown in the below image.
In the next article, I am going to discuss jQuery Mouse Events with Examples. Here, in
this article, I try to explain jQuery Change Event with Examples and I hope you enjoy
this jQuery Change Event article.
Mouse Events in jQuery
Events are often triggered by the user's interaction with the web page, such as when a
link or button is clicked, text is entered into an input box or textarea, selection is made in
a select box, key is pressed on the keyboard, the mouse pointer is moved etc. In some
cases, the Browser itself can trigger the events, such as the page load and unload events.
Mouse Events in jQuery
The Mouse Event represents events that occur due to the user interacting with a
pointing device (such as a mouse). Common events using this interface include click,
double click, mouse, mouse enter, mouse out, etc.
If you want to attach any handler with these mouse events, then jQuery provides a bunch
of mouse event handling methods. In this article, we will learn about these mouse events.
List of jQuery Mouse Events
Here is the list of mouse events used in jQuery.
1. click(): The event occurs when the user clicks on an element
2. contextmenu(): The event occurs when the user right-clicks on an element to open a
context menu
3. dblclick(): The event occurs when the user double-clicks on an element
4. hover(): attach one or two handlers to the matched elements, to be executed when
the mouse pointer enters and leaves the elements.
5. mouseenter(): The event occurs when the pointer is moved onto an element
6. mouseleave(): The event occurs when the pointer is moved out of an element
7. mouseover(): The event occurs when the pointer is moved onto an element, or onto
one of its children
8. mouseout(): The event occurs when a user moves the mouse pointer out of an
element, or out of one of its children
Syntax:
All the events take a handler function as parameter for example,
$(selector).mouseenter( function(){} ) or
$(selector).mouseleave( function(){} )
But hover() method can take two handlers as parameters. The first one is for mouse enter
and the second one is for mouse leave
$(selector).hover(handlerIn, handlerOut)
Actually, this is the shorthand for
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
Example: jQuery Mouse Click Event
The jQuery click() method attach an event handler function to the selected elements for
"click" event. The attached function is executed when the user clicks on that element.
The following example will hide the <p> elements on a page when they are clicked.
Now by some examples, we will see that how to attach event handlers to these events.
Let’s see the click event first. In the below example, we have <div> element. When we
will click on the div notice at the change i.e. it will append the text You clicked the div as
well as also change the background color of the div element to yellow.
<h2>jQuery Mouse Events</h2>
<section>
<div>
<h3>This is a Title</h3>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi,
laudantium.
</p>
</div>
</section>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("div").click(function () {
$(this).css("background-color", "yellow");
$("div p").append("<br>" + "You clicked the div");
});
});
</script>
Now, run the above code and you will see the following page in the browser. Now, click
anywhere between the div element which shown in between the red color as shown in the
below image.

Once you click anywhere between the div element, then the text “You clicked the div”
is appended as well as the background color of the div element is changed to yellow as
shown in the below image.

Example: jQuery dblclick mouse event - In the below example, we will see the jQuery
dblclick mouse event. In the below example, when we will double click on the <div>,
notice that we are adding a new class to the div.
<style>
.test {
background-color: rgb(120, 247, 215);
font-style: italic;
font-weight: 700;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
border: 2px solid black;
border-radius: 20px;
}
</style>
<h2>jQuery dblclick Event</h2>
<section>
<div>
<h3>This is a Title</h3>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi,
laudantium.
</p>
</div>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("div").dblclick(function () {
$(this).addClass("test");
});
});
</script>
Now, run the above code and you will see the following page in the browser. Now, double
click anywhere between the div element which shown in between the red color as shown
in the below image.

Once you double click anywhere between the div element, then the class test is applied to
the div element as shown in the below image.

Example: jQuery right-click event (contextmenu()) - Now, we will see the right-click
event. In the below example, we are using contextmenu() event. When we will right-click
on the <div> the div will be faded and a text will be appended to the <p> element.
<h2>jQuery contextmenu Event</h2>
<section>
<div>
<h3>This is a Title</h3>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi,
laudantium.
</p>
</div>
</section>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("div").contextmenu(function () {
$("div").fadeTo(500, 0.4);
$("div p").append("<br><br><i>You have Right Clicked the
div</i>");
});
});
</script>
Now, run the above code and you will see the following web page in the browser. Now,
right-click anywhere between the div element which shown in between the red color as
shown in the below image.

Once you right-click anywhere between the div element, then the test is appended to the
div element as shown in the below image.

Example: jQuery mouse up and mouse down event - Now, we will see the jQuery
mouse down and mouse up event. In the below example, mousedown() event is triggered
when you press any mouse button, and mouseup() event is triggered when you release
that button.
<style>
.test {
background-color: rgb(120, 247, 215);
font-style: italic;
font-weight: 700;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
0 6px 6px rgba(0, 0, 0, 0.23);
border: 2px solid black;
border-radius: 20px;
}
</style>
<h2>jQuery mouse up and mouse down event</h2>
<section>
<div>
<h3>This is a Title</h3>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nisi,
laudantium.
</p>
</div>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("div")
.mousedown(function () {
$(this).addClass("test");
})
.mouseup(function () {
$(this).removeClass();
});
});
</script>
Now run the above code, and then press and hold the mouse button and you will see that
the mousedown event is fired and the test class is applied to the div element as shown in
the below image.

Once you release the press button, the mouseup event is fired and it will remove the test
class from the div element and you will see the following output in the browser.
Example: jQuery Mouse Enter and Mouse Leave event
Now, we will see mouse enter and mouse leave event. In the below example, we have
designed a card. If you enter the mouse cursor on the card then the container will be
displayed.
<style>
body {
background-color: #ddd;
font-family: Arial, Helvetica, sans-serif;
}
.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
transition: 0.3s;
width: 30%;
margin: auto;
}
img {
width: 100%;
height: 300px;
}

.card:hover {
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
cursor: pointer;
}

.container {
padding: 10px 16px;
display: none;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 10px 25px;
margin: 10px 0;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<div class="card">
<img src="C:\Users\HP\OneDrive\Pictures\img_avatar.JPG"
alt="Avatar" />
<div class="container">
<h4><b>John Doe</b></h4>
<p>Web Developer & Designer</p>
<button>Know More</button>
</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(".card")
.mouseenter(function () {
$(".container").show(500);
})
.mouseleave(function () {
$(".container").hide(500);
});
</script>
Now, run the above code and once you enter the mouse cursor on the card then the
container will be displayed as shown in the below image.

Now leave the mouse cursor and the container will be removed and you will see the
following page in the browser.
Now the above code can be shortened by the hover() method. We already know the
syntax. 1st handler is for mouse enter and 2 nd handler is for mouse leave event. So, modify
the script section of the same example as follows to use the mouse hover method and will
produce the same result.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(".card").hover(
function () {
$(".container").show(500);
},
function () {
$(".container").hide(500);
}
);
</script>
Keyboard Events
A keyboard event is fired when the user press or release a key on the keyboard. Here're
some commonly used jQuery methods to handle the keyboard events.
The keypress() Method - The jQuery keypress() method attach an event handler
function to the selected elements (typically form controls) that is executed when the
browser receives keyboard input from the user. The following example will display a
message when the kypress event is fired and how many times it is fired when you press
the key on the keyboard.
<script>
$(document).ready(function(){
var i = 0;
$('input[type="text"]').keypress(function(){
$("span").text(i += 1);
$("p").show().fadeOut();
});
});
</script>
Note: The keypress event is similar to the keydown event, except that modifier and non-
printing keys such as Shift, Esc, Backspace or Delete, Arrow keys etc. trigger keydown
events but not keypress events.
The keydown() Method - The jQuery keydown() method attach an event handler
function to the selected elements (typically form controls) that is executed when the user
first presses a key on the keyboard. The following example will display a message when
the keydown event is fired and how many times it is fired when you press the key on the
keyboard.
<script>
$(document).ready(function(){
var i = 0;
$('input[type="text"]').keydown(function(){
$("span").text(i += 1);
$("p").show().fadeOut();
});
});
</script>
The keyup() Method - The jQuery keyup() method attach an event handler function to
the selected elements (typically form controls) that is executed when the user releases a
key on the keyboard. The following example will display a message when the keyup event
is fired and how many times it is fired when you press and release a key on the keyboard.
<script>
$(document).ready(function(){
var i = 0;
$('input[type="text"]').keyup(function(){
$("span").text(i += 1);
$("p").show().fadeOut();
});
});
</script>
Tip: The keyboard events can be attached to any element, but the event is only sent to
the element that has the focus. That's why the keyboard events generally attached to the
form controls such as text input box or textarea.
jQuery Event Object
jQuery Event Object
When a W3C event listener’s event occurs and it calls its associated function, it also
passes a single argument to the function – a reference to the event object. The event
object contains a number of properties that describe the event that occurred. For
example, the event object contains event data like, the X and Y coordinates of the mouse
pointer when the event occurred, the HTML element that fired the event, which mouse
button is clicked, etc.
Query’s event system normalizes the event object according to W3C Standards. The
event object is guaranteed to be passed to the event handler. Most properties from the
original event are copied over and normalized to the new event object.
Here the list of event object properties is given
1. event.currentTarget: The current DOM element within the event bubbling phase.
2. event.data: An optional object of data passed to an event method when the current
executing handler is bound.
3. event.delegateTarget: Returns the element where the currently-called jQuery event
handler was attached.
4. event.isDefaultPrevented(): Returns whether event.preventDefault() was ever
called on this event object.
5. event.isImmediatePropagationStopped():
Returns whether event.stopImmediatePropagation() was ever called on this event
object.
6. event.isPropagationStopped(): Returns whether event.stopPropagation() was ever
called on this event object.
7. event.metaKey: Indicates whether the Windows key or Command key (on Mac
keyboard) was pressed when the event fired.
8. event.namespace: Returns the namespace specified when the event was triggered.
9. event.pageX: Returns the mouse position relative to the left edge of the document.
10. event.pageY: Returns the mouse position relative to the top edge of the
document.
11. event.preventDefault(): If this method is called, the default action of the event
will not be triggered.
12. event.relatedTarget: Returns the other DOM element involved in the event, if
any.
13. event.result: The last or previous value returned by an event handler that was
triggered by this event.
14. event.stopImmediatePropagation(): Keeps the rest of the handlers from being
executed and prevents the event from bubbling up the DOM tree.
15. event.stopPropagation(): Prevents the event from bubbling up the DOM tree,
preventing any parent handlers from being notified of the event.
16. event.target: Returns the DOM element that triggered the event.
17. event.timeStamp: Returns difference in milliseconds between the time the event
is triggered and January 1, 1970.
18. event.type: Returns the type of event that was triggered.
19. event.which: Indicates the specific key or button that was pressed for key or
mouse events.
Example: jQuery Event Object
Obtaining the event object is very simple. The event object is always passed to the event
handler method. Let us understand this with an example. When we click the button, we
want to retrieve the following event properties
1. Name of the event.
2. X co-ordinate of the mouse pointer when the event occurred.
3. Y co-ordinate of the mouse pointer when the event occurred.
4. Type of the DOM element that was triggered due to the event.
5. The tag name of the DOM element that was triggered due to the event.
In the below example, we are passing event objects to getEventDetails() method. This
object is the raw JavaScript event object. The type property gives us the event name that
occurred. pageX and pageY properties return the X and Y coordinates of the mouse
pointer. Target property returns the HTML element that raised the event. Target, pageX,
and pageY properties are supported by all modern browsers and Internet Explorer 9 and
above. The below example code will not work in Internet Explorer 8 and earlier versions.
In addition to the click event, the following example returns mouseover and mouseout
event data.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
#btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
#btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>jQuery Event Object</h1>
<div class="container">
<input
id="btn"
type="button"
value="Use me to retrieve the event properties"
/>
<p id="Result"></p>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn")
.click(function () {
getEventDetails(event);
})
.mouseover(function () {
getEventDetails(event);
})
.mouseout(function () {
getEventDetails(event);
});

function getEventDetails(event) {
var eventDetails = `Event =
${event.type}
<br/> X =
${event.pageX}
<br/>Y =
${event.pageY}
<br/>Target Type =
${event.target.type}
<br/>Target Tag Name =
${event.target.tagName}
`;

$("#Result").html(eventDetails);
}
});
</script>
Now run the above code and you will get the following output in the browser.

Now when you mouseover over the “Use me to retrieve the event properties”, the
mouseover event is fired and it will give the event details as shown in the below image.
Now when you mouse out from the “Use me to retrieve the event properties”, the mouse
out event is fired and it will give the event details as shown in the below image.

Now when you click on the “Use me to retrieve the event properties”, the click event is
fired and you will get the event details as shown in the below image.
Cross Browser Solution: For the above code (our first example) to work in all browsers
including Internet Explorer 8 and earlier versions, we need to pass the event object to
the mouse events such as click(), mouseover() & mouseout(). When the event object is
passed inside the callback of jQuery mouse events, that is going to be the jQuery event
object. As we know jQuery normalizes the event object for cross-browser support. So, the
following code is going to work in all browsers.
<h1>jQuery Event Object</h1>
<div class="container">
<input
id="btn"
type="button"
value="Use me to retrieve the event properties"
/>

<p id="Result"></p>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn")
.click(function (event) {
getEventDetails(event);
})
.mouseover(function (event) {
getEventDetails(event);
})
.mouseout(function (event) {
getEventDetails(event);
});

function getEventDetails(event) {
var eventDetails = `Event =
${event.type}
<br/> X =
${event.pageX}
<br/>Y =
${event.pageY}
<br/>Target Type =
${event.target.type}
<br/>Target Tag Name =
${event.target.tagName}
`;

$("#Result").html(eventDetails);
}
});
</script>
The above example will give you the same output as the previous example.
Example: Now let us see some more event object properties. In the below example, we
are using event.currentTarget, event.delegateTarget, event.timeStamp, event.metaKey,
and event.relatedTarget propertirs.
<h1>jQuery Event Object</h1>
<div class="container">
<input
id="btn"
type="button"
value="Use me to retrieve the event properties"
/>

<p id="Result"></p>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn").mouseover(function (event) {
getEventDetails(event);
});

function getEventDetails(event) {
var eventDetails = `Event Target=
${event.currentTarget.type}
<br/>Delegate Target =
${event.delegateTarget.type}
<br/> Time Stamp =
${event.timeStamp}
<br/>Meta Key =
${event.metaKey}
<br/>Related Target =
${event.relatedTarget.tagName}
`;

$("#Result").html(eventDetails);
}
});
</script>
Now run the above code and put the mouse pointer on the Use me to retrieve the event
properties button and you will get the following output.

Example: event.preventDefault() and event.isDefaultPrevented() - In the below


example, we will see the two properties i.e. event.preventDefault() and
event.isDefaultPrevented().
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
a {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
a:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>jQuery Event Object</h1>
<div class="container">
<a href="https://www.google.com/" id="prevent"
>www.google.com(Prevent Default)</a
>
<a href="https://www.google.com/">www.google.com</a>

<p id="Result"></p>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("#prevent").click(function (event) {
event.preventDefault();
$("#Result").html(event.isDefaultPrevented());
});
});
</script>
The default behavior of the anchor tag is to redirect to the given address. But we can
prevent that default behavior. Notice that in the first anchor tag we have used prevent
default method. This is not going to www.google.com. And in the result <p> the Boolean
value is showing that we have used the prevent default method in the event as shown in
the below image.

But when you click on the 2nd button, it is navigating to the www.google.com
Example: event.stopPropagation() and event.isPropagationStopped() - In the
below example, we are going to learn event.stopPropagation() and
event.isPropagationStopped() method.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
.container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background-color: rgb(164, 255, 192);
padding: 20px;
border: 2px solid black;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
.demo {
margin: 20px auto;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 90%;
padding: 20px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 15px 20px;
text-align: center;
text-decoration: none;
outline: none;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
}
#result {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
</style>
<div class="container">
<h1>jQuery event object</h1>
<p class="demo">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Voluptatum,
odio neque veritatis ullam velit illum at obcaecati necessitatibus
quos
eveniet.
</p>
<button>Click Me</button>
<p id="result"></p>
</div>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("div").click(function () {
alert("Div element is clicked");
});
$("h1").click(function () {
alert("h1 element is clicked");
});
$("p").click(function () {
alert("P element is clicked");
});
$("button").click(function (event) {
event.stopPropagation();
alert("Button element is clicked");
$("#result").html(event.isPropagationStopped());
});
});
</script>
Notice this carefully. Click on the <p> element. At first alert for the p element is
displayed as shown in the below image.

Once you click on the OK button, the alert for the div element is displayed as shown in
the below image.
Then the alert for <div> element is also displayed. Because <p> is inside the <div> and
when we click on the p element <div> is also clicked actually. This is called event
bubbling. To prevent this we use event.stopPropagation(). Now, click on the Click Me
button, which is also inside the <div> but we have prevented that event from bubbling.

Here only the alert for the button is displayed. Once you click on the OK button, the
Boolean value is showing that we have used stop propagation in the event as shown in
the below image.

How to detect which mouse button is clicked using jQuery


How to detect which mouse button is clicked using jQuery
When a mouse event occurs (such as click, mouse up, or mouse down), the event object is
automatically passing to the event handler function. Now when we talk about event
objects there are two flavors of them, one is raw JavaScript Event Object and another is
jQuery event object. If we are using JavaScript Event Object and the browser is IE 8 or
lower versions then we use event.button property to detect which mouse button is
clicked.
event.button
1. Left Mouse Button
2. Middle Mouse Button
3. Right Mouse Button
While using JavaScript Event Object, and the browser is IR 8+ or any other browser then
we use event.which property to detect which mouse button is clicked
event.which
1. Left Mouse Button
2. Middle Mouse Button
3. Right Mouse Button
Now if we have to write JavaScript code for the detection of mouse button which will be
cross-browser support, then we have to code in the following way.
Using Raw JavaScript to detect which mouse button is clicked
Here in this example, if event.which property exists in the browser then it will execute
the ‘if’ block. Otherwise, it will go to the else block and our event.button property.
<h1>How to detect which mouse button is clicked using jQuery</h1>
<div class="container">
<button onmouseup="whichMouseButtonClicked(event)">
Click me to see which button you have clicked
</button>
<p id="Result"></p>
</div>
<script type="text/javascript">
function whichMouseButtonClicked(event) {
var ButtonClicked;
if (event.which) {
switch (event.which) {
case 1:
ButtonClicked = "Left Mouse Clicked";
break;
case 2:
ButtonClicked = "Middle Mouse Clicked";
break;
case 3:
ButtonClicked = "Right Mouse Clicked";
break;
default:
ButtonClicked = "Option Not Found..";
break;
}
} else {
switch (event.button) {
case 1:
ButtonClicked = "Left Mouse Clicked";
break;
case 4:
ButtonClicked = "Middle Mouse Clicked";
break;
case 2:
ButtonClicked = "Right Mouse Clicked";
break;
default:
ButtonClicked = "Option Not Found..";
break;
}
}

document.getElementById("Result").innerHTML = ButtonClicked;
}
Now run the above code and you will get the following output in the browser.

Now right click on the mouse over the Click me to see which button you have clicked
button and you will get the following output.

Now left-click on the mouse over the Click me to see which button you have clicked
button and you will get the following output.

Now click on the Middle mouse over the Click me to see which button you have clicked
button and you will get the following output.
Using jQuery to detect which mouse button is clicked - Now let’s see how to
achieve the same functionality i.e. which mouse button is clicked using jQuery. In the
below example, inside the callback of mousedown event, the event object which we are
passing is a jQuery event object, not a raw JavaScript event object.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
button:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>How to detect which mouse button is clicked using jQuery</h1>
<div class="container">
<button>Click me to see which button you have
clicked</button></br></br>
<p></p>
</div>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").mousedown(function (event) {
switch (event.which) {
case 1:
$("p").html("Left Mouse Clicked");
break;
case 2:
$("p").html("Middle Mouse Clicked");
break;
case 3:
$("p").html("Right Mouse Clicked");
break;
default:
$("p").html("Option Not Found..");
}
});
});
</script>
The above code will give you the same output as the previous example. jQuery normalizes
which property of the event object is fired and it will work across all browsers. The
amount of code you have to write is a lot less. Thus, jQuery provides a more efficient way.
Binding Event Handlers using jQuery on Method
Binding Event Handlers using jQuery on Method
jQuery On() method
The on() method in jQuery attaches one or more event handlers for selected elements or
children elements and specifies a function to run when the event occurs. As of jQuery
version 1.7, the on() method is the new replacement for the bind() method. This method
brings a lot of consistency to the application, and jQuery recommends using the on()
method to attach event handlers.
Syntax: $(selector).on(event, childSelector, data, function, map)
Parameters:
1. event: Required. Specifies one or more event(s) or namespaces to attach to the
selected elements. Multiple event values are separated by space. Must be a valid
event.
2. childSelector: Optional. Specifies that the event handler should only be attached to
the specified child elements.
3. data: Optional. Specifies additional data to pass along to the function.
4. function: Required. Specifies the function to run when the event occurs.
5. map: Specifies an event map ({event:function, event:function, …}) containing one or
more events to attach to the selected elements, and functions to run when the events
occur.
Example: Bind Click Event using jQuery ON Method - At first, let us look at a simple
example where we have to bind a click event to a button using the on() method. In the
below example, we have used the on() method to bind the event “click” to the button. The
usage of the bind() and on() methods are very similar. What you have to do, just put on()
instead of bind().
<h1>jQuery Bind Events Using ON Method</h1>
<input id="btn" type="button" value="Click Me to see the changes" />
<p id="Result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn").on("click", function () {
$("#Result").html("You have clicked the button");
});
});
</script>
Now, run the above code and you will get the following output.

Now click on the Click Me to see the changes button and you will see the following
output in the browser.

Example: Bind Multiple Events using jQuery ON Method - Now let us see how to
bind multiple events to an element. When you are binding multiple events, those events
should gap by a “space”. In the below example, we have bound two events to the card.
When you will hover on the card the details will be shown. When you leave your pointer
out the details will be hidden.
body {
background-color: #ddd;
font-family: Arial, Helvetica, sans-serif;
}
.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
transition: 0.3s;
width: 30%;
margin: auto;
}
img {
width: 100%;
height: 300px;
}

.card:hover {
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
cursor: pointer;
}

.container {
padding: 10px 16px;
display: none;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 10px 25px;
margin: 10px 0;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<div class="card">
<img src="C:\Users\HP\OneDrive\Pictures\img_avatar.jpg"
alt="Avatar" />
<div class="container">
<h4><b>John Doe</b></h4>
<p>Web Developer & Designer</p>
<button>Know More</button>
</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(".card").on("mouseenter mouseleave", function () {
$(".container").toggle(500);
});
</script>
Example: jQuery ON Method using Map - Now let’s see how to use event map using
on() method. In the below example, we are using event map inside the on() method in this
syntax: $(selector).on({event:function(){}, event:function(){}, …})
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
#btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
#btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>jQuery Bind Events using on()</h1>
<input id="btn" type="button" value="Use Me to see the changes" />
<p id="Result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#btn").on({
click: function () {
$("#Result").html(
`Mouse pointer is at ( ${event.pageX}, ${event.pageY} )`
);
},
mouseenter: function () {
$("body").css("background-color", "#bfbfbf");
},
mouseleave: function () {
$("body").css("background-color", "#fff");
},
});
});
</script>
When you will hover on the button, you will get the following output.

When you will put your pointer out of the button, you will get the following output.

When you click on the button, you will get the following output.
jQuery off() method
The off() method is used to remove event handlers from selected elements or children of
elements. This method can remove selected event handlers, or stop specified functions
from running when the event occurs. This method can also unbind event handlers using
an event object. This is used to unbind an event from within itself (like removing an event
handler after the event has been triggered a certain number of times).
As of jQuery version 1.7, the off() method is the new replacement for the unbind()
method. This method brings a lot of consistency to the application, and jQuery
recommends using the off() method to remove event handlers.
Syntax: $(selector).off(event, selector, function(eventObj), map)
Parameter
1. event: Required. Specifies one or more events or namespaces to remove from the
selected element(s). Multiple event values are separated by a space. Must be a valid
event
2. selector: Optional. A selector which should match the one originally passed to the
on() method when attaching event handlers
3. function(eventObj): Optional. Specifies the function to run when the event occurs
4. map: Specifies an event map ({event:function, event:function, …}) containing one or
more event to attach to the elements, and functions to run when the events occur
Example: jQuery off() method - In the below example, we will see that how to unbind
some events using the off method which is already attached. In the below example, we
are binding the events when we are clicking on the “On event” button. Then we are
unbinding the events by clicking the corresponding buttons
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
margin-bottom: 40px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
.btn-group .button {
background-color: #3c7072;
border: 1px solid rgb(36, 109, 103);
outline: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
font-size: 16px;
cursor: pointer;
float: left;
}

.btn-group .button:not(:last-child) {
border-right: none;
}

.btn-group .button:hover {
background-color: #194849;
}
</style>
<h1>jQuery on() & off() method</h1>
<button class="btn" id="btn">Hey I'm a button !</button>
<div class="btn-group">
<button id="on" class="button">on event</button>
<button id="offClick" class="button">off click event</button>
<button id="offEnter" class="button">off mouse enter event</button>
</div>
<p id="Result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#on").click(function () {
$("#btn").html("Now you can use me !!");
$("#btn").on({
click: function () {
alert("You Clicked the Button");
},
mouseenter: function () {
$("body").css("background-color", "#bfbfbf");
},
mouseleave: function () {
$("body").css("background-color", "#fff");
},
});
});
$("#offClick").click(function () {
$("#btn").html("Oops !! Click event removed");
$("#btn").off("click");
});
$("#offEnter").click(function () {
$("#btn").html("Oh no !! mouse enter is gone");
$("#btn").off("mouseenter");
});
});
</script>
When you run the above code, you will get the following output.

1. Click on the event. Now you can use the button to see the click(), mouseenter() &
mouseleave() methods
2. Click on the ‘off click event’ button. Now the click event is removed. No functionality
will occur if you click the button. But mouse enter event will work
3. Now click on the ‘off mouse enter event’. That mouse enter event will also not work
Example: jQuery On and Off Method - In the below example, we will see that how to
remove the event object by the off() method. In this example, you can enlarge this image
2 times. After that, we are removing the event object and then if you further double click
on the image, a message will be shown.
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
img {
width: 300px;
height: 300px;
transition: 0.3s;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
</style>
<h1>Double Click to Zoom the image</h1>
<img src="C:\Users\HP\OneDrive\Pictures\MyImage.JPG" alt="image" />
<p id="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
var x = 0;
$("img").dblclick(function (event) {
$(this).css({ width: "+=100px", height: "+=100px" });
x++;
if (x >= 2) {
$(this).off(event);
$("img").dblclick(function () {
$("#result").html("you cannot zoom this image further");
});
}
});
});
</script>
Now, double click two times on the image and it will be enlarging. But when you double
click the third time on the image, it will give you the following message.
Passing Data to Event Handler in jQuery
jQuery event.data Property
In jQuery, we have learned that the event handler function automatically receives the
event object. We have discussed a number of built-in properties on the event object. In
this article, we will see the event.data property of the event object. This property helps to
pass any data to the event handler function.
Syntax: We have learned the syntax of the event handler earlier using the on() method.
$(selector).on(event, childSelector, data, function, map)
This data parameter is the data in the form of an object which we want to pass to the
event handler function. When we will want to use that data, we can retrieve that by
event.data.
Example: Passing Data to Event Handler in jQuery - As you can see in the below
code, here, we are passing an object as a parameter to the on() method. And when we are
printing that on the console, we are using event.data
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>
<body>
<h1>Passing data to the event handler</h1>
<button>Hey! You can click me</button>
<p id="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").on(
"click",
{ name: "John Doe", message: "you are beautiful" },
function (event) {
console.log(event.data);
}
);
});
</script>
</body>
</html>
Now run the above code and open the browser developer tool by pressing the F12 key
and select the Console tab. Then click on the Hey! You can click me button and you
should see the following logs in the Console tab as shown in the below image.

Now, these properties can also be accessed by the event.data.name and


event.data.message. To prove this, modify the script section of the code as follows of
the same example.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").on(
"click",
{ name: "John Doe", message: "you are beautiful" },
function (event) {
$("#result").html(`Hey ${event.data.name}, ${event.data.message}`);
}
);
});
</script>
Notice we have successfully passed our custom data to the event handler function. Now,
run the code and then click on the Hey! You can click me button and you should get the
message as shown in the below image.
Example: Passing Data to Event Handler in jQuery
In this example, we are passing an object inside the on() method. When you will click on
each paragraph you can see the message we are passing through the data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 70%;
padding: 20px;
margin: 30px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 20px 35px;
text-align: center;
text-decoration: none;
outline: none;
display: inline-block;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
</head>
<body>
<h1>Passing data to the event handler</h1>

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


<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("p").each(function (index) {
$(this).on(
"click",
{ message: `This is the paragraph indexed at ${index}` },
function (event) {
$(this).append("</br>" + event.data.message);
}
);
});
});
</script>
</body>
</html>
Now run the above code and you will get the following output.

Now click on each paragraph and you will get the following output.
Add Event Handlers to Dynamically Created Elements in jQuery
How to add Event Handlers to Dynamically Created Elements? In the previous
articles, we have learned that how to attach the event handler to DOM elements. Now the
question arises if that element is not present in our DOM and that is being added by our
script. Let us understand this problem by practical example first.
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px auto;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 100%;
padding: 20px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 20px 35px;
text-align: center;
text-decoration: none;
outline: none;
display: inline-block;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<h1>Add Event Handlers to Dynamically Created Elements</h1>
<div class="container">
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
</div>
<button id="btn">Add a new paragraph element</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("p").on("click", function () {
$(this).fadeOut(500);
});

$("#btn").on("click", function () {
var newParagraph = "<p>New Paragraph</p>";
$(".container").append(newParagraph);
});
});
</script>
Look at the above example, here, we have already some <p> elements in our DOM. And
by clicking the button we are creating new <p> elements. Now run the above code, and
you will get the following output,
Now, click on the Add a new paragraph element button to add new paragraphs as shown
in the below image.

Now click on the paragraph items.


You can see that when you click on the existing <p> elements they fade out. But when
you click on the new <p> elements nothing happens. What is the reason for that?
When the document is ready to execute to the script, we have bound the click event
handler to all the <p> element which is present in the DOM but not to those elements
which are being added by the script. That’s why they are not fading out. Now, what can
we do about that? Let’s see.
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px auto;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 100%;
padding: 20px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 20px 35px;
text-align: center;
text-decoration: none;
outline: none;
display: inline-block;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<h1>Add Event Handlers to Dynamically Created Elements</h1>
<div class="container">
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
</div>
<button id="btn">Add a new paragraph element</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("p").on("click", function () {
$(this).fadeOut(500);
});

$("#btn").on("click", function () {
var newParagraph = $("<p>New Paragraph</p>").on("click", function
() {
$(this).fadeOut(500);
});

$(".container").append(newParagraph);
});
});
</script>
Here we are wrapping the new paragraphs. Run the above code and click on the Add a
new paragraph element button to add new paragraphs.
Now click on the paragraphs and you will see that existing, as well as new paragraphs,
are fade out.
Now you can see that existing, as well as new <p> elements, are fading out. Our problem
is solved. But there is a problem. The problem with this approach is that we are binding a
click event handler to every <p> item. This means if you have 500 <p> items, then there
will be 500 event handlers in the memory and this may negatively affect the performance
of your application.
A better way of doing the same from a performance standpoint is shown below. In this
example, the click event handler is attached to the parent element (div). Even if you have
500 <p> items, there is only one click event handler in memory.
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px auto;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 100%;
padding: 20px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 20px 35px;
text-align: center;
text-decoration: none;
outline: none;
display: inline-block;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<h1>Add Event Handlers to Dynamically Created Elements</h1>
<div class="container">
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
</div>
<button id="btn">Add a new paragraph element</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$(".container").on("click", "p", function () {
$(this).fadeOut(500);
});

$("#btn").on("click", function () {
$(".container").append("<p>New Paragraph</p>");
});
});
</script>
The above example will give you the same output as the previous example.
How does this work?
1. When you click on a <p>, the event gets bubbled up to its parent (div.container) as
the <p> does not have an event handler
2. The bubbled event is handled by the parent element, as it has a click event handler.
3. When a new <p> is added dynamically, you don’t have to add the click event handler
to it. Since the newly created <p> is added to the same parent element
(div.container), the click event of this <p> also gets bubbled up to the same parent
and will be handled by it.
jQuery Event Delegation and UnDelegation
Event delegation in JavaScript is a pattern that efficiently handles events. Events can be
added to a parent element instead of adding to every single element. It refers to the
process of using event propagation (bubbling) to handle events at a higher level in the
DOM than the element on which the event originated. This can be done on a particular
target element using the .target property of an event object.
A Brief Intro to Event Propagation - By default, events triggered on an element
propagate up the DOM tree to the element's parent, its ancestors, and on up until the
root element (html). Look at this example:
<div>
<span>
<button>Click Me!</button>
</span>
</div>
Here we have a div which is a parent of a span which in turn is a parent of
the button element. Due to event bubbling, when the button receives an event, say click,
that event bubbles up the tree, so span and div will respectively receive the event also.
How Does Event Delegation Work?
With event delegation, instead of handling the click event on the button, you can handle
it on the div. The idea is that you "delegate" the handling of an event to a different
element (in this case, the div, which is a parent element) instead of the actual element
(the button) that received the event. Here's what I mean by that in code:
const div = document.getElementsByTagName("div")[0]
div.addEventListener("click", (event) => {
if(event.target.tagName === 'BUTTON') {
console.log("button was clicked")
}
});
The event object has a target property which contains information about the element that
actually received the event. On target.tagName, we get the name of the tag for the
element, and we check if it's BUTTON. With this code, when you click the button, the
event bubbles up to the div which handles the event.
Benefits of Event Delegation
It is useful because the event can be listened to on multiple elements by using just one
event handler. It also uses less memory and gives better performance. Apart from this, it
also requires less time for setting up the event handler on the page. Using event
delegation has the following benefits:
 Better performance and less usage of memory
 The time required for setting up an event handler on the page is less
 The document object is available immediately and the element is rendered perfectly
without any delay.
 Easy syntax and usage
What do I mean by this? Look at this code:
<div>
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
</div>
Here we have 3 buttons. Let's say we wanted to handle a click event on each button, such
that when it is clicked, the button's text is logged to the console. We can implement that
like this:
const buttons = document.querySelectorAll('button')
buttons.forEach(button => {
button.addEventListener("click", (event) => {
console.log(event.target.innerText)
})
})
I'm using querySelectorAll here as it returns a NodeList which I can use
the forEach method for. getElementsByTagName returns an HTMLCollection which
doesn't have the forEach method.
When you click on the first button, you have "Button 1" logged on the console. For the
second button, "Button 2" is logged, and for the third button, "Button 3" is logged.
Although this works as we want, we have created three event listeners for the three
buttons.
Since the click event on these buttons propagates upward in the DOM tree, we can use a
common parent or ancestor that they have to handle the event. In this case, we delegate
a common parent that they share to handle the logic we want.
Here's how:
const div = document.querySelector('div')
div.addEventListener("click", (event) => {
if(event.target.tagName === 'BUTTON') {
console.log(event.target.innerText)
}
})
Now, we have just one event listener, but the same logic: when you click the first button,
"Button 1" is logged to the console, and the same thing for the other buttons.
Even if we add an extra button like this:
<div>
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<button>Button 4</button>
</div>
We won't have to change the JavaScript code as this new button also shares
the div parent (which we delegated for the event handling) with the other buttons.
Example: Let's take an example and understand event delegation in JavaScript.
Steps to create event delegation
 Create an HTML file
 Create a JavaScript file and use the function document.getElementById and give the
id of the element where event delegation is to be applied.
 Use the function addEventListener by passing the parameter onclick and function(e).
As soon as the events take place, the function is called which is passed to the listener.
JavaScript code
const table = document.getElementById("mynewtable")
table.addEventListener("click", function(e){
console.log(e);
const target = e.target;

if (target){
e.target.style.color = 'Brown';
}
});
HTML code
<html>
<head>
</head>
<body bgcolor="#ddd">
<h3>Changing the table’s font color</h3>
<h5> Click on a text in a cell for changing its background color</h5>
<table id = "mynewtable">
<tr>
<h3>
<td style="color:Red"> Red </td>
<td style="color:yellow"> Yellow </td>
<td style="color:green"> Green </td>
</h3>
</tr>
</table>
</body>
</html>
3 Steps for Using Event Delegation
Following are the steps for using event delegation:
Determine the parent of elements to watch for events- In the example given, <table id =
"mynewtable"> is the parent element of the table.
Parent element is the one from which the feature is inherited in the child elements.
Attach the event listener to the parent element
- document.getElementById() addEventListener('click', handler), is used for attaching the
event listeners to the parent element. This button when clicked reacts because of the
event listener.
Use event.target to select the target element- When the element is clicked, the handler
function in JS is invoked with the event object as an argument. The event.target property
is the element on which the event is dispatched.
jQuery Event Delegation - Event delegation allows us to attach a single event listener,
to a parent element, that will fire for all descendants matching a selector, whether those
descendants exist now or are added in the future. Actually, in the previous article, we
have used event delegation. In this example, we have used the event delegation by the
on() method.
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px auto;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 100%;
padding: 20px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 20px 35px;
text-align: center;
text-decoration: none;
outline: none;
display: inline-block;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<h1> jQuery event delegation </h1>
<div class="container">
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
</div>
<button id="btn">Add a new paragraph element</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$(".container").on("click", "p", function () {
$(this).fadeOut(500);
});

$("#btn").on("click", function () {
$(".container").append("<p>New Paragraph</p>");
});
});
</script>
Now run the above code and you will get the following output.

Now click on the Add a new paragraph element button to add new paragraphs as shown
in the below image. I have clicked two times, so two new paragraphs are added as shown
below.
Now click on each paragraph (existing plus newly added paragraphs) and you will see
that all the paragraphs are faded away as shown in the below image.

So let us understand once again how does this work:


1. When you click on a <p>, the event gets bubbled up to its parent (div.container) as
the <p> does not have an event handler
2. The bubbled event is handled by the parent element, as it has a click event handler.
3. When a new <p> is added dynamically, you don’t have to add the click event handler
to it. Since the newly created <p> is added to the same parent element
(div.container), the click event of this <p> also gets bubbled up to the same parent
and will be handled by it.
Now jQuery provides another method to perform event delegation i.e. delegate() method.
jQuery Delegate() Method: The delegate() method attaches one or more event
handlers for specified elements that are children of selected elements and specifies a
function to run when the events occur. Event handlers attached using the delegate()
method will work for both current and FUTURE elements (like a new element created by
a script).
Syntax: $(selector).delegate(childSelector, event, data, function)
Notice that, parameters of the delegate() method are the same as the on() method but the
difference is in order. In the delegate() method, the child selector comes first as a
parameter then the type of the event. Now let’s look at how to achieve the previous
functionality using the delegate() method.
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px auto;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 100%;
padding: 20px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 20px 35px;
text-align: center;
text-decoration: none;
outline: none;
display: inline-block;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<h1> jQuery event delegation </h1>
<div class="container">
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
</div>
<button id="btn">Add a new paragraph element</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$(".container").delegate("p", "click", function () {
$(this).fadeOut(500);
});

$("#btn").on("click", function () {
$(".container").append("<p>New Paragraph</p>");
});
});
</script>
Notice that we have used delegate() method instead of the on() method. If you are using
jquery version 1.7 or above then jQuery recommends using the on() method over the
delegate method. This is working exactly in the same manner as the previous example.
jQuery Event Undelegation
jQuery event undelegation is used to detach any event from a set of selected elements.
This can be done by using the off() or the undelegate() method
jQuery undelegate() method: The undelegate() method removes one or more event
handlers, added with the delegate() method.
Syntax: $(selector).undelegate(childSelector, event, function)
Notice that, the order of the parameters is the reverse of that of the off() method. In the
off() method, you know that type of event comes first and then the selector.
Example: jQuery Event Undelegation
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px auto;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 100%;
padding: 20px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 15px 20px;
text-align: center;
text-decoration: none;
outline: none;
display: inline-block;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<h1>jQuery event delegation</h1>
<div class="container">
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
</div>
<div>
<button id="btnadd">Add a new paragraph element</button>
<button id="undelegate">Undelegate</button>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$(".container").delegate("p", "click", function () {
$(this).fadeOut(500);
});

$("#btnadd").on("click", function () {
$(".container").append("<p>New Paragraph</p>");
});
$("#undelegate").click(function () {
$(".container").off("click", "p");
});
});
</script>
Notice that here we are removing the click event handler from the <p> elements of the
container. Here we are using the off() method to achieve that. Now run the above code
and click on the Add a new paragraph element button to add new paragraphs as shown in
the below image.
Now click on the Paragraphs and you will see that the paragraphs are fading out as
shown in the below image.

Now click on the undelegate button. Once you click on the undelegated button, then click
on the paragraph items and you will see that nothing is happening. That event handler is
removed now. This is called the event undelegation. This can also be done with the
undelegate method. Modify the script section as shown below.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$(".container").delegate("p", "click", function () {
$(this).fadeOut(500);
});

$("#btnadd").on("click", function () {
$(".container").append("<p>New Paragraph</p>");
});
$("#undelegate").click(function () {
$(".container").undelegate("p", "click");
});
});
</script>
Here we are using the undelegate method but look at the order of the parameters. Here
the child selector “p” comes first. Then the type of the event. The output is going to be
exactly the same.
Event Delegation using jQuery Live Function
Event Delegation using jQuery Live Function with Examples
In this article, I am going to discuss Event Delegation using the jQuery Live
function with Examples. In our previous two articles, we have discussed how to perform
event delegation using on() and delegate() methods. Another way to perform event
delegation is by using the jQuery live() function.
jQuery Live Function() - The live() method attaches one or more event handlers for
selected elements and specifies a function to run when the events occur. Event handlers
attached using the live() method will work for both current and Future elements
matching the selector (like a new element created by a script).
Syntax: $(selector).live(event, data, function)
Parameters:
1. event: Required. Specifies one or more events to attach to the elements. Multiple
event values are separated by space. Must be a valid event.
2. data: Optional. Specifies additional data to pass along to the function.
3. function: Required. Specifies the function to run when the event occurs
Note: The live() method was deprecated in jQuery version 1.7, and removed in version
1.9
jQuery die() function
The die() method removes one or more event handlers, added with the live() method, for
the selected elements.
Syntax: $(selector).die(event, function)
Parameters:
1. event: Required. Specifies one or more event handlers to remove. Multiple event
values are separated by space. Must be a valid event.
2. function: Optional. Specifies a specific function to remove.
Note: The die() method was deprecated in jQuery version 1.7, and removed in version
1.9.
Example: jQuery Live Function() - The example that we worked with in previous
articles is rewritten using the jQuery live() and die() functions as shown below. Notice
that, to perform event delegation we are using the live() function, and to stop event
delegation we are using the die() function.
One important thing is that we have to work with the older jQuery version to show the
live() and die() method, because these were completely removed in version 1.9. So, we
are using version 1.7 here.
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px auto;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
width: 100%;
padding: 20px;
border-radius: 30px;
background-color: rgb(255, 164, 164);
cursor: pointer;
}
button {
background-color: #1c4450;
border: none;
color: white;
padding: 15px 20px;
text-align: center;
text-decoration: none;
outline: none;
display: inline-block;
font-size: 20px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
}
</style>
<h1>jQuery live function</h1>
<div class="container">
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
<p>This is a dummy paragraph</p>
</div>
<div>
<button id="btnadd">Add a new paragraph element</button>
<button id="undelegate">Undelegate</button>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("p").live("click", function () {
$(this).fadeOut(500);
});
$("#btnadd").live("click", function () {
$(".container").append("<p>New Paragraph</p>");
});
$("#undelegate").click(function () {
$("p").die("click");
});
});
</script>
With on() and delegate() functions the event gets bubbled up to the specified parent
element, whereas with the jQuery live() function the event gets bubbled up all the way to
the document object. So, we don’t need to specify the parent element div.container.
Notice that we are using each “<p>” element as selector for live() and die() function.
Now run the above code and you will get the following output.

Now add two new paragraphs by clicking on Add a new paragraph element two times.
Once you add two paragraphs it should looks as shown below.
Now click on the new and existing paragraphs and those will fade out as shown in the
below image.

Now click on the Undelegate button. Once you click on the Undelegate button, then click
on the Paragraph element and you will see nothing has happened i.e. the paragraph
elements will not fade out.
Example: jQuery Live and Die Function - In the below example, we are binding the
click event handler to <p> elements by live() method. And by the button, we are
detaching that click event handler from the <p> elements. Notice that, click on the <p>
elements, their size, and letter spacing changes. Further, on the button click event, we
have removed the click event attached to the paragraph element by using the jQuery die
function.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
transition: 0.5s;
}
.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
cursor: pointer;
}
</style>
<h1>jQuery live and die function</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click any p element to increase size and letterspacing.</p>

<button class="btn">
Remove event handlers, added with the live() method, for p elements
</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></
script>
<script>
function changeSize() {
$(this).animate({ fontSize: "+=5px" });
}

function changeSpacing() {
$(this).animate({ letterSpacing: "+=5px" });
}

$(document).ready(function () {
$("p").live("click", changeSize);
$("p").live("click", changeSpacing);
$("button").click(function () {
$("p").die("click", changeSize);
});
});
</script>
Now run the above application and you will get the following output.

Now click on the Paragraph elements and you will see that the text is enlarging as shown
in the below image.

Now, click on the button and then try to click on the paragraphs and you will see that
nothing is happening.
Again, the important thing that should be discussed
The jQuery live() function is deprecated in jQuery 1.7 and completely removed in jQuery
1.9. Everything that can be achieved with the following methods can be achieved by
using the jQuery on() function.
1. live()
2. bind()
3. delegate()
So, if you are using jQuery 1.7 or a higher version, jQuery recommends using the on()
function. We have learned everything about on() method.
How to Execute Event Only Once using jQuery
How to Execute jQuery Event Only Once? We know that when we attach an event
handler to an element using the jQuery on method that event is going to occur unlimited
times whenever we execute that event. But what if we have to execute that event handler
only once? In this article, we will discuss how to execute the event of an element only
once. Let us understand this with an example.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
#btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
#btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>How to Execute Event Only Once in jQuery</h1>
<div class="container">
<input id="btn" type="button" value="click me to see the changes" />
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#btn").on("click", function () {
alert("You clicked this button");
});
});
</script>
Now run the above code and every time you click on the button, you will get the
JavaScript alert as shown in the below image.

But we don’t want that. We want that we should get the alert only once. If you want to
execute the click event handler only once, then you will have to explicitly remove the
click event handler. The following script removes the click event handler using the
jQuery off() function after the alert is displayed. Just modify the script section of the
previous example as follows.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#btn").on("click", function () {
alert("You clicked this button");
$(this).off("click");
});
});
</script>
Now when you click on the button for the first time, then you will get the alert as shown
in the below image. But from the second time onwards when you click on the button, you
will not get the alert.

Now our desired functionality is achieved. Notice that the alert is displaying only once.
The jQuery one() function does exactly the same thing. The click event is raised only
once. On the first click, a JavaScript alert is displayed, but on subsequent clicks, nothing
happens. To prove this, modify the script section of the previous example as follows.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#btn").one("click", function () {
alert("You clicked this button");
});
});
</script>
With the above changes in place, now the JavaScript alert is displayed only once i.e. for
the first time.
jQuery one() method - The one() method attaches one or more event handlers for the
selected elements and specifies a function to run when the event occurs. When using the
one() method, the event handler function is only run Once for each element.
Syntax: $(selector).one(event, data, function)
Parameters:
1. event: Required. Specifies one or more events to attach to the elements. Multiple
event values are separated by space. Must be a valid event.
2. data: Optional. Specifies additional data to pass along to the function.
3. function: Required. Specifies the function to run when the event occurs.
The syntax and type of usage of one() method is exactly the same as the on() method but
in one() method the event handler executes only once. Let’s understand the one() method
more clearly with another example.
Example: jQuery one() method
The following example binds 3 events (mouseover, mouse out, click) using the jQuery on()
function.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
transition: 0.5s;
}
#btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
#btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>How to Execute Event Only Once in jQuery</h1>
<div class="container">
<input id="btn" type="button" value="click me to see the changes" />
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#btn").on({
mouseover: function () {
$("body").css("background-color", "#a3a3a3");
},
mouseout: function () {
$("body").css("background-color", "white");
},
click: function () {
alert("Hello from jQuery");
},
});
});
</script>
Notice in the above example, when you hover on the button the background color
changes as shown in the below image.

Now put your mouse cursor out of the button and it will back to normal i.e. the
background color removed as shown in the below image.
Now click on the button and you will get the alert as shown in the below image along
with the background color.

The changes are happening every time when we execute an event on the button. If we
want all these 3 events to execute only once, then we have to explicitly remove each
event after the first execution using the jQuery off() method. To do so, modify the script
section of the same example as follows.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#btn").on({
mouseover: function () {
$("body").css("background-color", "#a3a3a3");
$(this).off("mouseover");
},
mouseout: function () {
$("body").css("background-color", "white");
$(this).off("mouseout");
},
click: function () {
alert("Hello from jQuery");
$(this).off("click");
},
});
});
</script>
With the above changes in place, now, the events will execute only once. But in this case,
we are explicitly removing each event after the first execution. We can use the jQuery
one() method here. Let’s see how? Modify the Script section as shown below.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("#btn").one({
mouseover: function () {
$("body").css("background-color", "#a3a3a3");
},
mouseout: function () {
$("body").css("background-color", "white");
},
click: function () {
alert("Hello from jQuery");
},
});
});
</script>
Here we are using the jQuery one() method. Now this will produce exactly the same
result i.e. the events will execute only once.
Example: The jQuery one() function executes the handler at most once per element per
event type. In the following example, click, mouseover, and mouse ount events are
executed at most once for each button element.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
transition: 0.5s;
}
.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
</head>
<body>
<h1>How to Execute Event Only Once in jQuery</h1>
<div class="container">
<input class="btn" type="button" value="I am 1st Button" />
<input class="btn" type="button" value="I am 2nd Button" />
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(".btn").one({
mouseover: function () {
$("body").css("background-color", "#a3a3a3");
},
mouseout: function () {
$("body").css("background-color", "white");
},
click: function () {
alert("Hello from jQuery");
},
});
});
</script>
</body>
</html>
In the above example, we are having two buttons so we are using the class selector here.
And we have to execute the events once for each button. Hover on the 1 st button and you
will get the following output.

Hover on the 2nd button and you will get the following output.
Now click on the 1st button and you will get the following output.

Now click on the 2nd button and you will get the below output.

jQuery Prevent Default


jQuery Prevent Default
In this article, we will learn how to prevent this default behavior of the browser. First,
let’s look at some of the browser default actions. For example.
1. When you right-click on a web page or any link on the web page, the browser displays
the context menu
2. When you click on a link, the browser navigates to the page specified in the link
In some situations, you may want to prevent these default actions of the browser. For
example, some of the websites prevent you from right-clicking on the page. Disabling
right-click is annoying users. Many people say they disabled right-click for security
reasons because they do not want their content to be copied. But if you disable JavaScript
in the browser, you will still be able to right-click and copy the content. So, you are
achieving nothing by disabling right-click.
Let us now discuss, how to achieve this using jQuery. We have already learned the event
object. When you will pass that event object as a parameter of any callback of event
binding function then you have a built-in property on that event object i.e.
event.preventDefault().
event.preventDefault()
If this method is called, the default action of the event will not be triggered.
Parameters: This method does not accept any arguments.
Example: jQuery event.preventDefault() - In the below example, notice that in the
1st hyperlink we have used the prevent default method and we are appending that text in
p#Result. So if you click on the 1st hyperlink that will not be redirected. It will just show
the text. But when you click on the second button, it will redirect to the URL.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
a {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
a:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>jQuery Prevent Default</h1>
<div class="container">
<a href="https://www.google.com/" id="prevent">www.google.com(Prevent
Default)</a>
<a href="https://www.google.com/">www.google.com</a>
<p id="Result"></p>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("#prevent").click(function (event) {
event.preventDefault();
$("#Result").append(
"Default action of the hyperlink is prevented here</br>"
);
});
});
</script>
Now run the above code and click on the First button, you will see that it will not redirect
to the google home page and show the text as shown in the below image.

But when you click on the 2 nd hyperlink it will work as usual and navigate to the following
page.

Example: Disabling Right Click using jQuery - In the below example, notice that in
the 1st hyperlink we have used the prevent default method and we are appending that
text in p#Result. So if you right-click on the 1 st hyperlink that will not show the context
menu. It will just show the text on the result id
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
a {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}
a:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>jQuery Prevent Default</h1>
<div class="container">
<a href="https://www.google.com/" id="prevent">First Hyperlink(Prevent
Default)</a>
<a href="https://www.google.com/">Second Hyperlink</a>
<p id="Result"></p>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$("#prevent").contextmenu(function (event) {
event.preventDefault();
$("#Result").append(
"Default action of the context menu is prevented here</br>"
);
});
});
</script>
Now run the above code and then right-click on the first link and the context menu will
not be shown and you will see the appended text as shown in the below image.

But if you right-click on the 2 nd hyperlink it will show the context menu as expected as
shown in the below image.

jQuery Show and Hide Effects


jQuery show() and hide() Methods
You can show and hide HTML elements using the jQuery show() and hide() methods.
The hide() method simply sets the inline style display: none for the selected elements.
Conversely, the show() method restores the display properties of the matched set of
elements to whatever they initially were—typically block, inline, or inline-block—before
the inline style display: none was applied to them. Here's is an example.
<script>
$(document).ready(function(){
// Hide displayed paragraphs
$(".hide-btn").click(function(){
$("p").hide();
});
// Show hidden paragraphs
$(".show-btn").click(function(){
$("p").show();
});
});
</script>
You can optionally specify the duration (also referred as speed) parameter for making the
jQuery show hide effect animated over a specified period of time.
Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a
number of milliseconds, for greater precision; higher values indicate slower animations.
<script>
$(document).ready(function(){
// Hide displayed paragraphs with different speeds
$(".hide-btn").click(function(){
$("p.normal").hide();
$("p.fast").hide("fast");
$("p.slow").hide("slow");
$("p.very-fast").hide(50);
$("p.very-slow").hide(2000);
});

// Show hidden paragraphs with different speeds


$(".show-btn").click(function(){
$("p.normal").show();
$("p.fast").show("fast");
$("p.slow").show("slow");
$("p.very-fast").show(50);
$("p.very-slow").show(2000);
});
});
</script>
Note: The speed or duration string 'fast' indicates the durations of 200 milliseconds,
while the string 'slow' indicates the durations of 600 milliseconds.
You can also specify a callback function to be executed after the show() or hide() method
completes. We'll learn more about the callback function in upcoming chapters.
<script>
$(document).ready(function(){
// Display alert message after hiding paragraphs
$(".hide-btn").click(function(){
$("p").hide("slow", function(){
// Code to be executed
alert("The hide effect is completed.");
});
});

// Display alert message after showing paragraphs


$(".show-btn").click(function(){
$("p").show("slow", function(){
// Code to be executed
alert("The show effect is completed.");
});
});
});
</script>
jQuery toggle() Method
The jQuery toggle() method show or hide the elements in such a way that if the element
is initially displayed, it will be hidden; if hidden, it will be displayed (i.e. toggles the
visibility).
<script>
$(document).ready(function(){
// Toggles paragraphs display
$(".toggle-btn").click(function(){
$("p").toggle();
});
});
</script>
Similarly, you can specify the duration parameter for the toggle() method to make it
animated like the show() and hide() methods.
<script>
$(document).ready(function(){
// Toggles paragraphs with different speeds
$(".toggle-btn").click(function(){
$("p.normal").toggle();
$("p.fast").toggle("fast");
$("p.slow").toggle("slow");
$("p.very-fast").toggle(50);
$("p.very-slow").toggle(2000);
});
});
</script>
Similarly, you can also specify a callback function for the toggle() method.
<script>
$(document).ready(function(){
// Display alert message after toggling paragraphs
$(".toggle-btn").click(function(){
$("p").toggle(1000, function(){
// Code to be executed
alert("The toggle effect is completed.");
});
});
});
</script>
jQuery Scroll Event
jQuery scroll() method - The scroll event is raised when the user scrolls to a different
place in the element. It applies to window objects, but also to scrollable frames and
elements with the overflow CSS property set to scroll. The scroll() attaches a function to
run when a scroll event occurs.
Syntax: $(selector).scroll(function)
Parameters:
1. function: Optional. Specifies the function to run when the scroll event is triggered
Example: In the below example, we are triggering the scroll event. When the scroll
event will be triggered the <p> element will be displayed and at that moment it will be
faded out.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.container {
overflow: scroll;
background-color: rgb(221, 221, 221);
line-height: 1.5;
padding: 20px;
width: 600px;
height: 300px;
border: 2px solid black;
border-radius: 20px;
font-size: 20px;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
display: none;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>jQuey Scroll Event</h1>
<div class="container">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum
ducimus
cumque eveniet enim cupiditate voluptates id doloremque iure ut
ratione
aliquam, laborum maiores vel corporis tenetur vitae quia omnis quod
veniam
eos! Optio ducimus …
dolorum.
</div>
<p class="result">Scroll event triggered</p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("div").scroll(function () {
$("p").css("display", "block").fadeOut(1000);
});
});
</script>
Now run the above code and scroll down and you will get the following output.

Example: The following example keeps track of how many times the scroll event is
raised. Here we have used a variable counter. Whenever you raised the scroll event this
value of the counter is added by 1 and is displayed.
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.container {
overflow: scroll;
background-color: rgb(221, 221, 221);
line-height: 1.5;
padding: 20px;
width: 600px;
height: 300px;
border: 2px solid black;
border-radius: 20px;
font-size: 20px;
}
p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>jQuey Scroll Event</h1>
<div class="container">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum
ducimus
cumque eveniet enim cupiditate voluptates id doloremque iure ut
ratione
aliquam, laborum maiores vel corporis tenetur vitae quia omnis quod
veniam
eos! Optio ducimus voluptate quidem. Perspiciatis deleniti incidunt …
</div>
<p class="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
var counter = 0;
$("div").scroll(function () {
$("p").html(`The scroll event triggered ${(counter += 1)} times`);
});
});
</script>
Now run the above code and then scroll down and you will get the output something
below. Here, the number of times will be varying.
jQuery scrollTop() & scrollLeft() method
The scrollTop() & scrollLeft() method sets or returns the vertical & horizontal scrollbar
position respectively for the selected elements. When the scrollbar is on the top, the
position is 0 and when the scrollbar is on the far left side, the position is 0.
Syntax:
When used to return the position:
1. $(selector).scrollTop()
2. $(selector).scrollLeft()
Set vertical and horizontal scrollbar position:
1. $(selector).scrollTop(position)
2. $(selector).scrollLeft(position)
Parameters:
1. position: Specifies the vertical scrollbar position in pixels.
Example:
In the below example, we are returning the position of the div whenever scrolled.
<h1>jQuey Scroll Event</h1>
<div class="container">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum
ducimus
cumque eveniet enim cupiditate voluptates id doloremque iure ut
ratione
aliquam, laborum maiores vel corporis tenetur vitae quia omnis quod
veniam
eos! Optio ducimus ..
</div>
<p class="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("div").scroll(function () {
let topPosition = $("div").scrollTop();
$("p").html(`Top : ${topPosition}`);
});
});
</script>
Now run the above code and scroll down and you will get the following output.

Example:
The following example keeps track of whether the user scrolled up or down.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1>jQuey Scroll Event</h1>
<div class="container">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum
ducimus
cumque eveniet enim cupiditate voluptates id doloremque iure ut
ratione
aliquam, laborum maiores vel corporis tenetur vitae quia omnis quod
veniam
eos! Optio ducimus voluptate quidem. Perspiciatis deleniti incidunt …
</div>
<p class="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(document).ready(function () {
var lastScrollTop = 0;
$("div").scroll(function () {
var currentScrollPosition = $(this).scrollTop();
if (currentScrollPosition > lastScrollTop) {
$("p").text("You scrolled down");
} else {
$("p").text("You scrolled up");
}
lastScrollTop = currentScrollPosition;
});
});
});
</script>
</body>
</html>
Example: In the below example, notice that no matter where ever you are in the <div>
by scrolling, if you click on the button “Go to top” you will reach the top.
<style>
body {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}

button {
background-color: #1c4450;
border: none;
color: white;
padding: 20px 35px;
margin: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 20px;
border-radius: 50px;
cursor: pointer;

.container {
overflow: scroll;
background-color: rgb(221, 221, 221);
line-height: 2;
padding: 20px;
width: 600px;
height: 300px;
border: 2px solid black;
border-radius: 20px;
font-size: 20px;
scroll-behavior: smooth;
}

p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}
</style>
<h1>jQuey Scroll Event</h1>
<div class="container">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolorum
ducimus
cumque eveniet enim cupiditate voluptates id doloremque iure ut ratione
aliquam, laborum maiores vel corporis tenetur vitae quia omnis quod
veniam
eos! …
</div>
<button>Go to top</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("div").scrollTop(0);
});
});
</script>
Now run the above code and scroll down and then click on the Go to Top button and you
will move to the top position.
jQuery Fading Effects
jQuery fadeIn() and fadeOut() Methods
You can use the jQuery fadeIn() and fadeOut() methods to display or hide the HTML
elements by gradually increasing or decreasing their opacity.
<script>
$(document).ready(function(){
// Fading out displayed paragraphs
$(".out-btn").click(function(){
$("p").fadeOut();
});

// Fading in hidden paragraphs


$(".in-btn").click(function(){
$("p").fadeIn();
});
});
</script>
Like other jQuery effects methods, you can optionally specify the duration or speed
parameter for the fadeIn() and fadeOut() methods to control how long the fading
animation will run. Durations can be specified either using one of the predefined
string 'slow' or 'fast', or in a number of milliseconds; higher values indicate slower
animations.
<script>
$(document).ready(function(){
// Fading out displayed paragraphs with different speeds
$(".out-btn").click(function(){
$("p.normal").fadeOut();
$("p.fast").fadeOut("fast");
$("p.slow").fadeOut("slow");
$("p.very-fast").fadeOut(50);
$("p.very-slow").fadeOut(2000);
});

// Fading in hidden paragraphs with different speeds


$(".in-btn").click(function(){
$("p.normal").fadeIn();
$("p.fast").fadeIn("fast");
$("p.slow").fadeIn("slow");
$("p.very-fast").fadeIn(50);
$("p.very-slow").fadeIn(2000);
});
});
</script>
Note: The effect of fadeIn()/fadeOut() method looks similar to show()/hide(), but
unlike show()/hide() method the fadeIn()/fadeOut() method only animates the opacity of
the target elements and does not animates their dimensions.
You can also specify a callback function to be executed after
the fadeIn() or fadeOut() method completes. We'll learn more about the callback function
in upcoming chapters.
<script>
$(document).ready(function(){
// Display alert message after fading out paragraphs
$(".out-btn").click(function(){
$("p").fadeOut("slow", function(){
// Code to be executed
alert("The fade-out effect is completed.");
});
});

// Display alert message after fading in paragraphs


$(".in-btn").click(function(){
$("p").fadeIn("slow", function(){
// Code to be executed
alert("The fade-in effect is completed.");
});
});
});
</script>
jQuery fadeToggle() Method - The jQuery fadeToggle() method display or hide the
selected elements by animating their opacity in such a way that if the element is initially
displayed, it will be fade out; if hidden, it will be fade in (i.e. toggles the fading effect).
<script>
$(document).ready(function(){
// Toggles paragraphs display with fading
$(".toggle-btn").click(function(){
$("p").fadeToggle();
});
});
</script>
Similarly, you can specify the duration parameter for the fadeToggle() method
like fadeIn()/fadeOut() method to control the duration or speed of the fade toggle
animation.
<script>
$(document).ready(function(){
// Fade Toggles paragraphs with different speeds
$(".toggle-btn").click(function(){
$("p.normal").fadeToggle();
$("p.fast").fadeToggle("fast");
$("p.slow").fadeToggle("slow");
$("p.very-fast").fadeToggle(50);
$("p.very-slow").fadeToggle(2000);
});
});
</script>
Similarly, you can also specify a callback function for the fadeToggle() method.
<script>
$(document).ready(function(){
// Display alert message after fade toggling paragraphs
$(".toggle-btn").click(function(){
$("p").fadeToggle(1000, function(){
// Code to be executed
alert("The fade-toggle effect is completed.");
});
});
});
</script>
jQuery fadeTo() Method - The jQuery fadeTo() method is similar to
the .fadeIn() method, but unlike .fadeIn() the fadeTo() method lets you fade in the
elements to a certain opacity level.
$(selector).fadeTo(speed, opacity, callback);
The required opacity parameter specifies the final opacity of the target elements that can
be a number between 0 and 1. The duration or speed parameter is also required for this
method that specifies the duration of the fade to animation.
<script>
$(document).ready(function(){
// Fade to paragraphs with different opacity
$(".to-btn").click(function(){
$("p.none").fadeTo("fast", 0);
$("p.partial").fadeTo("slow", 0.5);
$("p.complete").fadeTo(2000, 1);
});
});
</script>
jQuery Sliding Effects
jQuery slideUp() and slideDown() Methods
The jQuery slideUp() and slideDown() methods is used to hide or show the HTML
elements by gradually decreasing or increasing their height (i.e. by sliding them up or
down).
<script>
$(document).ready(function(){
// Slide up displayed paragraphs
$(".up-btn").click(function(){
$("p").slideUp();
});

// Slide down hidden paragraphs


$(".down-btn").click(function(){
$("p").slideDown();
});
});
</script>
Like other jQuery effects methods, you can optionally specify the duration or speed
parameter for the slideUp() and slideDown() methods to control how long the slide
animation will run. Durations can be specified either using one of the predefined
string 'slow' or 'fast', or in a number of milliseconds; higher values indicate slower
animations.
<script>
$(document).ready(function(){
// Sliding up displayed paragraphs with different speeds
$(".up-btn").click(function(){
$("p.normal").slideUp();
$("p.fast").slideUp("fast");
$("p.slow").slideUp("slow");
$("p.very-fast").slideUp(50);
$("p.very-slow").slideUp(2000);
});

// Sliding down hidden paragraphs with different speeds


$(".down-btn").click(function(){
$("p.normal").slideDown();
$("p.fast").slideDown("fast");
$("p.slow").slideDown("slow");
$("p.very-fast").slideDown(50);
$("p.very-slow").slideDown(2000);
});
});
</script>
You can also specify a callback function to be executed after
the slideUp() or slideDown() method completes. We'll learn more about the callback
function in upcoming chapters.
<script>
$(document).ready(function(){
// Display alert message after sliding up paragraphs
$(".up-btn").click(function(){
$("p").slideUp("slow", function(){
// Code to be executed
alert("The slide-up effect is completed.");
});
});

// Display alert message after sliding down paragraphs


$(".down-btn").click(function(){
$("p").slideDown("slow", function(){
// Code to be executed
alert("The slide-down effect is completed.");
});
});
});
</script>
jQuery slideToggle() Method - The jQuery slideToggle() method show or hide the
selected elements by animating their height in such a way that if the element is initially
displayed, it will be slide up; if hidden, it will be slide down i.e. toggles between
the slideUp() and slideDown() methods.
<script>
$(document).ready(function(){
// Toggles paragraphs display with sliding
$(".toggle-btn").click(function(){
$("p").slideToggle();
});
});
</script>
Similarly, you can specify the duration parameter for the slideToggle() method
like slideUp() and slideDown() methods to control the speed of the slide toggle animation.
<script>
$(document).ready(function(){
// Slide Toggles paragraphs with different speeds
$(".toggle-btn").click(function(){
$("p.normal").slideToggle();
$("p.fast").slideToggle("fast");
$("p.slow").slideToggle("slow");
$("p.very-fast").slideToggle(50);
$("p.very-slow").slideToggle(2000);
});
});
</script>
Similarly, you can also specify a callback function for the slideToggle() method.
<script>
$(document).ready(function(){
// Display alert message after slide toggling paragraphs
$(".toggle-btn").click(function(){
$("p").slideToggle(1000, function(){
// Code to be executed
alert("The slide-toggle effect is completed.");
});
});
});
</script>
jQuery Image Gallery
jQuery Image Gallery
Let’s see how to make Image Gallery using jQuery.
First, create a folder with the name Images within
the D drive and then put any 4 images with the
name PIC1.jpg, PIC2.jpg, PIC3.jpg, and PIC4.jpg
within the Images folder. The image gallery should
look as shown in the image below. When we click
on the thumbnail image, that image should be
displayed in the main image gallery.
Following is the complete source code of the image
gallery using jQuery. Let us write the code first
and then we will understand how it will work.
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}

body {
background: #fff;
min-height: 100vh;
background: linear-gradient(to right bottom, #273c75, #079992);
background-repeat: no-repeat;
}

img {
max-width: 100%;
}

.container {
padding: 40px 0;
}

figure {
max-width: 800px;
margin: 0 auto 40px;
border: 2px solid #fff;
}

figure img {
max-width: 100%;
min-width: 100%;
display: block;
height: 500px;
width: 540px;
box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0,
0.22);
}

ul {
list-style: none;
margin: 0;
text-align: center;
}

ul li {
margin: 0 5px;
display: inline-block;
width: 150px;
border: 1px solid #fff;
cursor: pointer;
}

ul li img {
display: block;
opacity: 0.4;
transition: 0.4s;
height: 100px;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0,
0, 0, 0.19)
}
</style>
<div class="container">
<figure>
<img id="mainImg" src="PIC1.jpeg">
</figure>
<ul>
<li><img src="PIC1.jpeg"></li>
<li><img src="PIC2.jpeg"></li>
<li><img src="PIC3.jpeg"></li>
<li><img src="PIC4.jpeg"></li>
</ul>
</div>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('ul img').on({
mouseover: function () {
$(this).css({
'opacity': 1
});
},
mouseout: function () {
$(this).css({
'opacity': 0.4
});
},
click: function () {
var imgURL = $(this).attr('src');
$('#mainImg').fadeOut(500, function () {
$(this).attr('src', imgURL);
}).fadeIn(500);
}
})
})
</script>
How this Image Gallery is Working? Notice the HTML. We have an id “mainImg”
where the actual image will be shown. And inside the <ul> element we have 4 <li>
elements in which the thumbnails are present. Then notice the jQuery. We have bound 3
events to each image in the <ul> i.e. mouseover, mouseout, and click.
When the event is ‘mouseover’ we are increasing the opacity. When the event is
‘mouseout’ we are decreasing the opacity again (This can be using hover in CSS easily
but here we are using just jQuery). When the event is ‘click’ you can see that we are
doing 3 steps
1. Retrieving the “src” attribute value on which thumbnail image is clicked
2. In the <img> element of id “mainImg”, fading out the present image and setting the
src attribute value
3. Again, fading in the clicked image
Thus, our image gallery is ready.
jQuery Optimized Image Gallery
jQuery Optimized Image Gallery with Examples
In this article, I am going to discuss How to Optimized jQuery Image Gallery with
Examples. Please read our previous article, where we discussed jQuery Image Gallery.
jQuery Optimized Image Gallery
In this article, we will make the image gallery of the previous article optimized and we
will add some extra features. The following things are to be done.
1. Optimize the performance speed of the gallery
2. Add the option for the user to select the animation effect and the animation duration
3. Add the option for zoom in and zoom out the image
Following is the complete source code of the optimized image gallery using
jQuery.
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}

body {
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-style: italic;
background: #fff;
min-height: 100vh;
background: linear-gradient(to right bottom, #273c75, #079992);
background-repeat: no-repeat;
}

.container {
padding: 40px 0;
}

#mainImg {
margin: 0 auto 40px;
display: block;
height: 500px;
width: 800px;
border: 2px solid #fff;
box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0,
0.22);
}

ul {
list-style: none;
margin: 0;
text-align: center;
}

ul li {
margin: 0 5px;
display: inline-block;
border: 1px solid #fff;
cursor: pointer;
}

ul li img {
display: block;
width: 150px;
height: 100px;
opacity: 0.4;
transition: 0.4s;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0,
0, 0, 0.19)
}

ul li img:hover {
opacity: 1;
}

.toolbox {
position: fixed;
right: 0;
top: 0;
display: flex;
justify-content: space-evenly;
align-items: center;
flex-direction: column;
height: 100%;
width: 150px;
}

select {
padding: 5px 8px;
margin: 10px auto;
width: 130%;
border: none;
font-size: 20px;
width: 80px;
cursor: pointer;
font-style: italic;
}

select:focus {
outline: none;
}

label {
font-size: 24px;
color: #fff;
}
input[type="button"] {
background-color: #e0e0e0;
border: none;
color: black;
padding: 10px 20px;
margin: 10px;
text-align: center;
text-decoration: none;
display: block;
font-size: 24px;
font-weight: 800;
border-radius: 50%;
cursor: pointer;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0,
0, 0, 0.19)
}
</style>
<div class="toolbox">
<label>Select Effect :
<select id="imgEffect">
<option value="Fade">Fade</option>
<option value="Slide">Slide</option>
</select></label>
<label>Time in seconds:
<select id="imgDuration">
<option value="0.5">0.5</option>
<option value="1">1</option>
<option value="1.5">1.5</option>
<option value="2">2</option>
<option value="2.5">2.5</option>
<option value="3">3</option>
</select></label>
<input id="btnEnlarge" type="button" value="+" />
<input id="btnShrink" type="button" value="-" />
</div>
<div class="container">
<img id="mainImg" src="PIC1.jpeg">
<ul>
<li><img src="PIC1.jpeg"></li>
<li><img src="PIC2.jpeg"></li>
<li><img src="PIC3.jpeg"></li>
<li><img src="PIC4.jpeg"></li>
</ul>
</div>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('ul').on("click", "img", function () {
var imageURL = $(this).attr('src');
var effect = $('#imgEffect').val();
var duration = $('#imgDuration').val() * 1000;
if (effect == "Fade") {
$('#mainImg').fadeOut(duration, function () {
$(this).attr('src', imageURL);
}).fadeIn(duration);
}
else {
$('#mainImg').slideUp(duration, function () {
$(this).attr('src', imageURL);
}).slideDown(duration);
}

);
var mainImg = $("#mainImg");
$("#btnEnlarge").click(function () {
mainImg.animate({ width: "+=100px", height: "+=100px" }, 500);

});
$("#btnShrink").click(function () {
mainImg.animate({ width: "-=100px", height: "-=100px" }, 500);

});

});
</script>
Steps:
1. Let’s first optimize the performance. Here you can notice that we are attaching the
event on the parent <ul> and inside the on() method we are using “IMG” as a Child
Selector parameter. Thus, fewer event handlers will be stored in memory.
2. We are retrieving the value of two select boxes what the user has selected and storing
those in variables “effect” & “duration”
3. Then we are using the condition that if the effect is “Fade” then the fade out-in code
will be executed otherwise the slide up-down
4. And in the duration parameter, instead of using any value manually, we are using the
parameter “duration” in which the user-selected duration is present
5. Finally, On the two buttons, we are attaching two click event handlers by which the
width and height property of the main image will be increased and decreased
respectively.
Output:
Now run the above code, and you will get the following output.
Now click on the plus (+) button to zoom in and the minus (-) button to zoom out the
image as shown in the below image.

jQuery Image Slideshow with Thumbnails


jQuery Image Slideshow with Thumbnails
In this article, we are going to transform the image gallery into an image slide show.
Let’s see how to build that image slide show. Following is the complete source code of
the image slide show.
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}

body {
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-style: italic;
background: #fff;
min-height: 100vh;
background: linear-gradient(to right bottom, #273c75, #079992);
background-repeat: no-repeat;
}

.container {
padding: 40px 0;
}

#mainImg {
margin: 0 auto 40px;
display: block;
height: 500px;
width: 800px;
border: 2px solid #fff;
box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0,
0.22);
}

ul {
list-style: none;
margin: 0;
text-align: center;
}

ul li {
margin: 0 5px;
display: inline-block;
border: 1px solid #fff;
cursor: pointer;
}

ul li img {
display: block;
width: 150px;
height: 100px;
opacity: 0.4;
transition: 0.4s;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0,
0, 0, 0.19)
}

ul li img:hover {
opacity: 1;
}

.toolbox {
position: fixed;
right: 0;
top: 0;
display: flex;
justify-content: space-evenly;
align-items: center;
flex-direction: column;
height: 100%;
width: 200px;
}

select {
padding: 5px 8px;
margin: 10px auto;
width: 130%;
border: none;
font-size: 20px;
width: 80px;
cursor: pointer;
font-style: italic;
}

select:focus {
outline: none;
}

label {
font-size: 24px;
color: #fff;
}

input[type="button"] {
background-color: #e0e0e0;
border: none;
color: black;
padding: 10px 20px;
margin: 10px;
text-align: center;
text-decoration: none;
display: block;
font-size: 24px;
font-weight: 800;
border-radius: 50px;
cursor: pointer;
transition: 0.4s;
box-shadow: 0 10px 12px 0 rgba(0, 0, 0, 0.20), 0 15px 40px 0 rgba(0,
0, 0, 0.15)
}

input[type="button"]:hover {
box-shadow: 0 19px 38px rgba(0, 0, 0, 0.30), 0 15px 12px rgba(0, 0, 0,
0.22);
}

input[type="button"]:disabled {
opacity: 0.4;
}
</style>
<div class="toolbox">
<input id="btnStartSlideShow" type="button" value="Start" />
<input id="btnStopSlideShow" type="button" value="Stop" />
</div>
<div class="container">
<img id="mainImg" src="PIC1.jpeg">
<ul>
<li><img src="PIC1.jpeg"></li>
<li><img src="PIC2.jpeg"></li>
<li><img src="PIC3.jpeg"></li>
<li><img src="PIC4.jpeg"></li>
</ul>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
var imageURLs = new Array();
var intervalId;
var btnStart = $("#btnStartSlideShow");
var btnStop = $("#btnStopSlideShow");

$('ul img').each(function () {
imageURLs.push($(this).attr('src'));
});

function setImage() {
var mainImageElement = $("#mainImg");
var currentImageURL = mainImageElement.attr('src');
var currentImageIndex = $.inArray(currentImageURL, imageURLs);

if (currentImageIndex == (imageURLs.length - 1)) {


currentImageIndex = -1;
}

mainImageElement.attr('src', imageURLs[currentImageIndex + 1]);


}

btnStart.click(function () {
intervalId = setInterval(setImage, 500);
$(this).attr('disabled', 'disabled');
btnStop.removeAttr('disabled');
});

btnStop.click(function () {
clearInterval(intervalId);
$(this).attr('disabled', 'disabled');
btnStart.removeAttr('disabled');
}).attr('disabled', 'disabled');
});
</script>
Steps:
1. First, we are making a new array “imageURLs” in which we are storing the ‘src’
attribute values of all thumbnail images.
2. Then we have created our function setImage(). In that, we are retrieving the src
attribute of the current image that is displayed on the #mainImg. And then we are
finding the index number of that in imageURLs array. If that current image index is
matching the index of the last element, then we are deliberately setting the current
image index to -1 so that when it will be increased by 1 it will have the index 0 i.e. the
first element. And then we are setting the src attribute value of the main image
element to the next indexed element of the array.
3. In the “Start” button we’re attaching a click event handler to execute setInterval()
method. And simultaneously we are disabling the “start” button and enabling the
“stop” button
4. In the “Stop” button we’re attaching a click event handler to execute clearInterval()
method. And simultaneously we are disabling the “stop” button and enabling the
“start” button.
Output: Now run the above code and you will get the following output. Click on the Start
button to start the Image slideshow and click on the stop button to stop the image
slideshow.

jQuery Animate Function


jQuery Animate Function
The animate() method performs a custom animation of a set of CSS properties. This
method changes an element from one state to another with CSS styles. The CSS property
value is changed gradually, to create an animation effect. Only numeric values can be
animated (like “margin:30px”). String values cannot be animated (like “background-
color:red”), for this you need a jQuery plug-in. You can use the strings “show”, “hide” and
“toggle” as values. These values allow hiding and showing the animated element.
Note: Use “+=” or “-=” for relative animations (like width ”+=30px”). This will increase
the width by 30px
Syntax: (selector).animate( {styles}, speed, easing, callback)
Parameters:
1. styles: Required. Specifies one or more CSS properties/values to animate. The
property names must be camel-cased when used with the animate() method: You will
need to write paddingLeft instead of padding-left, marginRight instead of margin-
right, and so on.
2. speed: Optional. Specifies the speed of the animation. The default value is 400
milliseconds. Possible values in milliseconds (like 100, 1000, 5000, etc.), “slow”, and
“fast”.
3. easing: Optional. Specifies the speed of the element in different points of the
animation. The default value is “swing”. Possible values: “swing” – moves slower at
the beginning/end, but faster in the middle. “linear” – moves in a constant speed
4. callback: Optional. A function to be executed after the animation completes.
Example1: jQuery Animate Function
<style>
body {
background-color: rgb(226, 225, 225);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}

img {
width: 600px;
height: 400px;
opacity: 0.4;
}

.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}

.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
</style>
<h1>jQuery Animate Function</h1>
<img src="D:\Images\MyImage.jpg" alt="photo">
<button class="btn">Click to Animate The Image</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$(document).ready(function () {
$("button").click(function () {
$("img").animate({ width: "800px", height: "600px", opacity:
"1" })
});
});
});
</script>
Now click on the button and you will see that the image will gradually increase its height
and width and opacity will be “1” as shown in the below image.
You can also increase or decrease the values of properties using “+=” or “-=” as follows.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("img").animate({ width: "+=200px", height: "+=200px", opacity:
"1" })
});
});
</script>
This will produce the same result.
Example2: Animate Function in jQuery - In the below example, we are using the
“speed”, “easing”, and “callback” parameters. Notice that we are setting the speed to
1500 ms, the easing to “linear” and in the callback, we are printing a text on the <p>
element.
<style>
body {
background-color: rgb(226, 225, 225);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}

.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}

.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}

.test {
width: 400px;
height: 80px;
background-color: rgb(152, 255, 203);
padding: 100px 0;
margin: 20px 0;
text-align: center;
font-size: 20px;
font-weight: 400;
border-radius: 20px;
border: 1px solid #000;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
position: relative;
}

p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
</style>
<h1>jQuery Animate Function</h1>
<div class="test">Hey! Beautiful People!!</div>
<button class="btn">Click to Animate The DIV</button>
<p id="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("div").animate({
left: "200px",
fontSize: "24px",
fontWeight: "800",
borderWidth: "5px"
}, 1500, "linear", function () {
$("p").html("Animation ended");
})
});
});
</script>
When you run the above code, you will get the following output.

In the above example, all the animations are happening in a parallel way. But if you want
the animations to happen one after another then you can use method chaining. In this
way, the animations will be executed in a queue. Modify the script section of the example
as shown below and see the output by clicking on the button.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("div")
.animate({ left: "200px" }, 1500)
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.animate({ borderWidth: "5px" }, 1500, function () {
$("p").html("Animation ended");
})
});
});
</script>
There is an alternate syntax of .animate() method
Syntax: (selector).animate({styles},{options})
Parameters:

Example 2 can be achieved by this syntax also


<style>
body {
background-color: rgb(226, 225, 225);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}

.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}

.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}

.test {
width: 400px;
height: 80px;
background-color: rgb(152, 255, 203);
padding: 100px 0;
margin: 20px 0;
text-align: center;
font-size: 20px;
font-weight: 400;
border-radius: 20px;
border: 1px solid #000;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
position: relative;
}

p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
</style>
<h1>jQuery Animate Function</h1>
<div class="test">Hey! Beautiful People!!</div>
<button class="btn">Click to Animate The DIV</button>
<p id="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("div").animate({
left: "200px",
fontSize: "24px",
fontWeight: "800",
borderWidth: "5px"
}, {
duration: 5000,
easing: "linear",
start: function () {
$("p").html("Animation started");
},
complete: function () {
$("p").html("Animation ended");
},
fail: function () {
$("p").html("Animation failed to execute");
}
})
});
});
</script>
jQuery Animation Queue
jQuery Animation Queue
When several calls to animate() method are chained together that is generally called the
animation queue. By default, these calls are placed into a queue to be executed one after
the other in series rather than executing all of them simultaneously in parallel. The name
of this queue is fx.
Example: Each HTML element has its own queue. In the following example, there will be
5 calls to the animate method placed in the queue of each div element. This means both
div elements (.test1 & .test2) may start to execute the first call to animate method more
or less at the same time. However, from the given queue the queued methods are
executed one after the other in series.
<style>
body {
background-color: rgb(226, 225, 225);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}

.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}

.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}

div {
width: 400px;
height: 40px;
padding: 100px 0;
margin: 10px 0;
text-align: center;
font-size: 20px;
font-weight: 400;
border-radius: 20px;
border: 1px solid #000;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
position: relative;
}

.test1 {
background-color: rgb(152, 255, 203);
}

.test2 {
background-color: rgb(255, 253, 140);
}

p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
</style>
<h1>jQuery Animate Function</h1>
<div class="test1">Hey! Beautiful People!!</div>
<div class="test2">Hey! You are awesome!!</div>
<button class="btn">Click to Animate The DIV</button>
<p id="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>

$(document).ready(function () {
$("button").click(function () {
$("div.test1")
.animate({ left: "200px" }, 1500)
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.animate({ borderWidth: "5px" }, 1500)
$("div.test2")
.animate({ left: "200px" }, 1500)
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.animate({ borderWidth: "5px" }, 1500)
});
});
</script>
Now run the above code and you will get the following output.

Now click on the button and you will get the following output.
Now let’s discuss the .queue() method of jQuery in brief
jQuery .queue() method
The queue() method shows the queue of functions to be executed on the selected
elements. A DOM element can have several queues. Most often it has only one, the “fx”
queue (as mentioned above), which is the default jQuery queue.
Syntax: $(selector).queue(queueName)
Parameter: queueName: Optional. Specifies the name of the queue
Example: Now let’s use this queue method. Here .queue() method is used to add a
function to the queue of div.test1 element. So inside that function, we are printing the
length of the queue which are waiting to be executed.
<style>
body {
background-color: rgb(226, 225, 225);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}

.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}

.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}

div {
width: 400px;
height: 40px;
padding: 100px 0;
margin: 10px 0;
text-align: center;
font-size: 20px;
font-weight: 400;
border-radius: 20px;
border: 1px solid #000;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
position: relative;
}

.test1 {
background-color: rgb(152, 255, 203);
}

.test2 {
background-color: rgb(255, 253, 140);
}

p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}
</style>
<h1>jQuery Animate Function</h1>
<div class="test1">Hey! Beautiful People!!</div>
<div class="test2">Hey! You are awesome!!</div>
<button class="btn">Click to Animate The DIV</button>
<p id="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("div.test1")
.animate({ left: "200px" }, 1500)
.queue(function () {
$("p").html("Queued Calls :" + $(this).queue("fx").length);
})
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.animate({ borderWidth: "5px" }, 1500)
$("div.test2")
.animate({ left: "200px" }, 1500)
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.animate({ borderWidth: "5px" }, 1500)
});
});
</script>
Now run the above code and you will get the following output.

Now click on the button and you will get the following output.
Look at the output and let’s first understand why the queued calls are 4. So, hereafter the
animation, notice that how many functions are waiting to be executed. One is the
callback of .queue() method and the 3 .animate() methods. So, the queued call count is 4.
Now another thing is that after the animation, the animation stops for .test1 div. Because
when we use the queue method we have to explicitly use the .dequeue() method. Then all
the animations will take place.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("div.test1")
.animate({ left: "200px" }, 1500)
.queue(function () {
$("p").html("Queued Calls :" + $(this).queue("fx").length);
$(this).dequeue();
})
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.animate({ borderWidth: "5px" },1500)
$("div.test2")
.animate({ left: "200px" }, 1500)
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.animate({ borderWidth: "5px" }, 1500)
});
});
</script>
With the above script in place, run the code and click on the button and you will see the
following output in the browser.

Example: Now again modify the script section as shown below.


<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("div.test1")
.animate({ left: "200px" }, 1500)
.queue(function () {
$("p").html("Queued Calls :" + $(this).queue("fx").length);
$(this).dequeue();
})
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.queue(function () {
$("p").append("</br>Queued Calls :" + $(this).queue("fx").length);
$(this).dequeue();
})
.animate({ borderWidth: "5px" },1500)
$("div.test2")
.animate({ left: "200px" }, 1500)
.animate({ fontSize: "24px" }, 1500)
.animate({ fontWeight: "800" }, 1500)
.animate({ borderWidth: "5px" }, 1500)
});
});
</script>
With the above script in place, run the code and then click on the button and you will get
the following output. When we add another .queue() after the 3 rd animation, notice that
the queued call length is 2 because one is the callback and the last .animate() function is
waiting to be executed.

In all these examples the animations are executing in a queue one after another in the
series. If you want to perform those simultaneously you have to use the option
{queue:false} while using method chaining. In that case, you have to use the alternate
syntax of the animate method.
N.B- In the previous article we have seen that if you include those CSS properties in an
object then also animations will execute simultaneously.
Example:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("div.test1")
.animate({ left: "200px" }, { duration: 1500, queue: false })
.animate({ fontSize: "24px" }, { duration: 1500, queue: false })
.animate({ fontWeight: "800" }, { duration: 1500, queue: false })
.animate({ borderWidth: "5px" })
$("div.test2")
.animate({ left: "200px" }, { duration: 1500, queue: false })
.animate({ fontSize: "24px" }, { duration: 1500, queue: false })
.animate({ fontWeight: "800" }, { duration: 1500, queue: false })
.animate({ borderWidth: "5px" }, { duration: 1500, queue: false })
});
});
</script>
With the above script in place, run the code and click on the button and you will get the
following output.

Example: Now let’s see how to disable all the animations. To globally disable all
animations you have to use $.fx.off = true or jQuery.fx.off = true
In the below example if the checked option is true then it is going to off all the
animations.
<style>
body {
background-color: rgb(226, 225, 225);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}

.btn {
background-color: #1c4450;
border: none;
outline: none;
color: white;
padding: 20px 35px;
margin: 20px;
text-align: center;
display: inline-block;
font-size: 16px;
border-radius: 10px;
cursor: pointer;
transition-duration: 0.4s;
text-transform: uppercase;
}

.btn:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}

div {
width: 500px;
height: 50px;
padding: 100px 0;
margin: 10px 0;
text-align: center;
font-size: 20px;
font-weight: 400;
border-radius: 20px;
border: 1px solid #000;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
position: relative;
}

.test1 {
background-color: rgb(152, 255, 203);
}

.test2 {
background-color: rgb(255, 253, 140);
}

p {
margin: 20px;
font-weight: bold;
font-size: 30px;
text-align: center;
font-style: oblique;
}

label {
font-size: 24px;
font-weight: 700;
margin-bottom: 20px;
color: rgb(75, 30, 30);
}

input[type="checkbox"] {
width: 30px;
height: 30px;
margin-right: 10px;
cursor: pointer;

}
</style>
<h1>jQuery Animate Function</h1>
<label for="off">
<input type="checkbox" id="off">Disable All the Animations
</label>
<div class="test1">Hey! Beautiful People!!</div>
<div class="test2">Hey! You are awesome!!</div>
<button class="btn">Click to Animate The DIV</button>
<p id="result"></p>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$("button").click(function () {
$.fx.off = $('#off').is(':checked');
$("div.test1")
.animate({ left: "200px" }, 600)
.animate({ fontSize: "24px" }, 600)
.animate({ fontWeight: "800" }, 600)
.animate({ borderWidth: "5px" }, 600)
$("div.test2")
.animate({ left: "200px" }, 600)
.animate({ fontSize: "24px" }, 600)
.animate({ fontWeight: "800" }, 600)
.animate({ borderWidth: "5px" }, 600)

});
});
</script>
Now run the above code and click on the button and you will see that the animation is
working. But once you check the Disable All the Animations check box and then if you
click on the button, then nothing is going to happen. Notice that no animations are
happening if you check that box as shown in the below image.
jQuery Stop Animations
jQuery stop() Method
The jQuery stop() method is used to stop the jQuery animations or effects currently
running on the selected elements before it completes.
The basic syntax of the jQuery stop() method can be given with:
$(selector).stop(stopAll, goToEnd);
The parameters in the above syntax have the following meanings:
 The optional stopAll Boolean parameter specifies whether to remove queued
animation or not. Default value is false, that means only the current animation will be
stopped, rest of the animations in the queue will run afterwards.
 The optional goToEnd Boolean parameter specifies whether to complete the current
animation immediately. Default value is false.
Here's a simple example that demonstrates the jQuery stop() method in real action in
which you can start and stop the animation on click of the button.
<script>
$(document).ready(function(){
// Start animation
$(".start-btn").click(function(){
$("img").animate({left: "+=150px"}, 2000);
});

// Stop running animation


$(".stop-btn").click(function(){
$("img").stop();
});
// Start animation in the opposite direction
$(".back-btn").click(function(){
$("img").animate({left: "-=150px"}, 2000);
});

// Reset to default
$(".reset-btn").click(function(){
$("img").animate({left: "0"}, "fast");
});
});
</script>
Note: The jQuery stop() method works for all jQuery effects such
as fading, sliding, animated show and hide effects as well as custom animations.
Here's one more example of this method in which, if you click the "Slide Toggle" button
again after starting the animation but before it is completed, the animation will begin in
the opposite direction immediately from the saved starting point.
<script>
$(document).ready(function(){
// Kill and toggle the current sliding animation
$(".toggle-btn").on("click", function(){
$(".box").stop().slideToggle(1000);
});
});
</script>
Creating Smooth Hover Effect
While creating the animated hover effect one of the common problem you may face is
multiple queued animations, when you place and remove the mouse cursor rapidly.
Because, in this situation mouseenter or mouseleave events are triggered quickly before
the animation complete. To avoid this problem and create a nice and smooth hover effect
you can add the stop(true, true) to the method chain, like this:
<script>
$(document).ready(function(){
$(".box").hover(function(){
$(this).find("img").stop(true, true).fadeOut();
}, function(){
$(this).find("img").stop(true, true).fadeIn();
});
});
</script>
Note: The jQuery method stop(true, true) clears all the queued animations and jumps the
current animation to the final value.
jQuery Getters & Setter
In this tutorial you will learn how to get or set the element's content and attribute value
as well as the from control value using jQuery.
jQuery Get or Set Contents and Values
Some jQuery methods can be used to either assign or read some value on a selection. A
few of these methods are text(), html(), attr(), and val().
When these methods are called with no argument, it is referred to as a getters, because it
gets (or reads) the value of the element. When these methods are called with a value as
an argument, it's referred to as a setter because it sets (or assigns) that value.
jQuery text() Method
The jQuery text() method is either used to get the combined text contents of the selected
elements, including their descendants, or set the text contents of the selected elements.
Get Contents with text() Method - The following example will show you how to get the
text contents of paragraphs:
<script>
$(document).ready(function(){
// Get combined text contents of all paragraphs
$(".btn-one").click(function(){
var str = $("p").text();
alert(str);
});

// Get text contents of the first paragraph


$(".btn-two").click(function(){
var str = $("p:first").text();
alert(str);
});
});
</script>
Note: The jQuery text() retrieves the values of all the selected elements (i.e. combined
text), whereas the other getters such as html(), attr(), and val() returns the value only
from the first element in the selection.
Set Contents with text() Method - The following example will show you how to set the
text contents of a paragraph:
<script>
$(document).ready(function(){
// Set text contents of all paragraphs
$(".btn-one").click(function(){
$("p").text("This is demo text.");
});

// Set text contents of the first paragraph


$(".btn-two").click(function(){
$("p:first").text("This is another demo text.");
});
});
</script>
Note: When the jQuery text(), html(), attr(), and val() methods are called with a value as
an argument it sets that value to every matched element.
jQuery html() Method
The jQuery html() method is used to get or set the HTML contents of the elements.
Get HTML Contents with html() Method - The following example will show you how
to get the HTML contents of the paragraph elements as well as a <div> element
container:
<script>
$(document).ready(function(){
// Get HTML contents of first selected paragraph
$(".btn-one").click(function(){
var str = $("p").html();
alert(str);
});

// Get HTML contents of an element with ID container


$(".btn-two").click(function(){
var str = $("#container").html();
alert(str);
});
});
</script>
Note: If multiple elements are selected, the html() method only returns the HTML
contents of the first element from the set of matched elements.
Set HTML Contents with html() Method
The following example will show you how to set the HTML contents of
the <body> element:
<script>
$(document).ready(function(){
// Set HTML contents for document's body
$("button").click(function(){
$("body").html("<p>Hello World!</p>");
});
});
</script>
jQuery attr() Method
You can use the jQuery attr() method to either get the value of an element's attribute or
set one or more attributes for the selected element.
Get Attribute Value with attr() Method - The following example will show you how
get the href attribute of the hyperlink i.e. the <a> element as well as the alt attribute of
an <img> element:
<script>
$(document).ready(function(){
// Get href attribute value of first selected hyperlink
$(".btn-one").click(function(){
var str = $("a").attr("href");
alert(str);
});

// Get alt attribute value of an image with ID sky


$(".btn-two").click(function(){
var str = $("img#sky").attr("alt");
alert(str);
});
});
</script>
Note: If multiple elements are selected, the attr() method only returns the attribute value
of the first element from the set of matched elements. - Set Attributes
with attr() Method
The following example will show you how to set the checked attribute of the checkbox.
<script>
$(document).ready(function(){
// Check all the checkboxes
$("button").click(function(){
$('input[type="checkbox"]').attr("checked", "checked");
});
});
</script>
The attr() method also allows you to set multiple attributes at a time. The following
example will show you how to set the class and title attribute for the <img> elements.
<script>
$(document).ready(function(){
// Add a class and title attribute to all the images
$("button").click(function(){
$("img").attr({
"class" : "frame",
"title" : "Hot Air Balloons"
});
});
});
</script>
jQuery val() Method
The jQuery val() method is mainly used to get or set the current value of the HTML form
elements such as <input>, <select> and <textarea>.
Get the Values of Form Fields with val() Method - The following example will show
you how to get the values of form controls:
<script>
$(document).ready(function(){
// Get value of a text input with ID name
$("button.get-name").click(function(){
var name = $('input[type="text"]#name').val();
alert(name);
});

// Get value of a textarea with ID comment


$("button.get-comment").click(function(){
var comment = $("textarea#comment").val();
alert(comment);
});

// Get value of a select box with ID city


$("button.get-city").click(function(){
var city = $("select#city").val();
alert(city);
});
});
</script>
Note: If multiple form elements are selected, the val() method only returns the value of
the first element from the set of matched elements.
Set the Values of Form Fields with val() Method
The following example will show you how to set the values of the form controls:
<script>
$(document).ready(function(){
// Set value of all the text inputs
$("button").click(function(){
var text = $(this).text();
$('input[type="text"]').val(text);
});
});
</script>
jQuery Dimensions
Understanding the jQuery Dimensions
jQuery provides several methods, such as height(), innerHeight(), outerHeight(), width(),
innerWidth() and outerWidth() to get and set the CSS dimensions for the elements. Check
out the following illustration to understand how these methods are calculating the
dimensions of an element's box.

jQuery width() and height() Methods


The jQuery width() and height() methods get or set the width and the height of the
element respectively. This width and height doesn't
include padding, border and margin on the element. The following example will return
the width and height of a <div> element.
<script>
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").width();
var divHeight = $("#box").height();
$("#result").html("Width: " + divWidth + ", " + "Height: " +
divHeight);
});
});
</script>
Similarly, you can set the width and height of the element by including the value as a
parameter within the width() and height() method. The value can be either a string
(number and unit e.g. 100px, 20em, etc.) or a number. The following example will set the
width of a <div> element to 400 pixels and height to 300 pixels respectively.
<script>
$(document).ready(function(){
$("button").click(function(){
$("#box").width(400).height(300);
});
});
</script>
Note: Use the jQuery width() or height() method if you want to use an element's width or
height in a mathematical calculation, since it returns the width and height property value
as a unit-less pixel value (e.g. 400). Whereas, the css("width") or css("height") methods
returns value with units (e.g. 400px).
jQuery innerWidth() and innerHeight() Methods
The jQuery innerWidth() and innerHeight() methods get or set the inner width and
the inner height of the element respectively. This inner width and height includes
the padding but excludes border and margin on the element. The following example will
return the inner width and height of a <div> element on the click of a button.
<script>
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").innerWidth();
var divHeight = $("#box").innerHeight();
$("#result").html("Inner Width: " + divWidth + ", " + "Inner Height:
" + divHeight);
});
});
</script>
Similarly, you can set the element's inner width and height by passing the value as a
parameter to the innerWidth() and innerHeight() method. These methods only alter the
width or height of the element's content area to match the specified value.
For example, if the current width of the element is 300 pixels and the sum of the left and
right padding is equal to 50 pixels than the new width of the element after setting the
inner width to 400 pixels is 350 pixels i.e. New Width = Inner Width - Horizontal
Padding. Similarly, you can estimate the change in height while setting the inner height.
<script>
$(document).ready(function(){
$("button").click(function(){
$("#box").innerWidth(400).innerHeight(300);
});
});
</script>
jQuery outerWidth() and outerHeight() Methods
The jQuery outerWidth() and outerHeight() methods get or set the outer width and
the outer height of the element respectively. This outer width and height
includes padding and border but excludes the margin on the element. The following
example will return the outer width and height of a <div> element on the click of a
button.
<script>
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").outerWidth();
var divHeight = $("#box").outerHeight();
$("#result").html("Outer Width: " + divWidth + ", " + "Outer Height:
" + divHeight);
});
});
</script>
You can also get the outer width and height that includes padding and border as well as
the margin of the element. For that just specify the true parameter for the outer width
methods, like outerWidth(true) and outerHeight(true).
<script>
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").outerWidth(true);
var divHeight = $("#box").outerHeight(true);
$("#result").html("Outer Width: " + divWidth + ", " + "Outer Height:
" + divHeight);
});
});
</script>
Similarly, you can set the element's outer width and height by passing the value as a
parameter to the outerWidth() and outerHeight() methods. These methods only alter the
width or height of the element's content area to match the specified value, like
the innerWidth() and innerHeight() methods.
For example, if the current width of the element is 300 pixels, and the sum of the left and
right padding is equal to 50 pixels, and the sum of the width of the left and right border
is 20 pixels than the new width of the element after setting the outer width to 400 pixels
is 330 pixels i.e. New Width = Outer Width - (Horizontal Padding + Horizontal Border).
Similarly, you can estimate the change in height while setting the outer height.
<script>
$(document).ready(function(){
$("button").click(function(){
$("#box").outerWidth(400).outerHeight(300);
});
});
</script>
jQuery Traversing
What is Traversing
The jQuery selectors we've seen so far only allow us to select the elements down the
DOM tree. But there are many occasions when you need to select a parent or ancestor
element; that is where jQuery's DOM traversal methods come into play. With these
traversal methods, we can go up, down, and all around the DOM tree very easily.
DOM traversing is one of the prominent features of the jQuery. To make the most it you
need to understand the relationships between the elements in a DOM tree.
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
The HTML code in the example above can be represented by the following DOM tree:

The above diagram showing the parent/child relationships between the elements:
 The <body> element is the parent of the <div> element, and an ancestor of
everything inside of it. The enclosed <div> element is
the parent of <h1>, <p> and <ul> elements, and a child of the <body> element.
 The elements <h1>, <p> and <ul> are siblings, since they share the same parent.
 The <h1> element is a child of the <div> element and a descendant of
the <body> element. This element does not have any children.
 The <p> element is the parent of <em> element, child of the <div> element and
a descendant of the <body> element. The containing <em> element is a child of
this <p> element and a descendant of the <div> and <body> element.
 Similarly, the <ul> element is the parent of the <li> elements, child of
the <div> element and a descendant of the <body> element. The
containing <li> elements are the child of this <ul> element and a descendant of
the <div> and <body> element. Also, both the <li> elements are siblings.
Note: In logical relationships, an ancestor is a parent, grandparent, great-grandparent,
and so on. A descendant is a child, grandchild, great-grandchild, and so on. Sibling
elements are those which share the same parent.
Traversing the DOM Tree
Now that you have understood the logical relationships between the elements in a DOM
tree. In the upcoming chapters you will learn how to perform various traversing
operations such as traversing up, down and sideways the DOM tree using the jQuery.
jQuery Traversing Ancestors
Traversing Up the DOM Tree
In logical relationships an ancestor is a parent, grandparent, great-grandparent, and so
on.
jQuery provides the useful methods such as parent(), parents() and parentsUntil() that
you can use to traverse up in the DOM tree either single or multiple levels to easily get
the parent or other ancestors of an element in the hierarchy.
jQuery parent() Method - The jQuery parent() method is used to get the direct parent
of the selected element.
The following example will highlight the direct parent element of the <li> which
is <ul> by adding the class .highlight on document ready.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("li").parent().addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery parents() Method - The jQuery parents() method is used to get the ancestors of
the selected element.
The following example will add a border around all the ancestor elements of
the <li> which are <ul>, <div>, <body> and the <html> elements.
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("li").parents().addClass("frame");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
You can optionally include one or more selector as a parameter within
the parents() method to filter your search for the ancestors. The following example will
apply the border around all the ancestors of the <li> that are <div> elements.
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("li").parents("div").addClass("frame");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery parentsUntil() Method - The jQuery parentsUntil() method is used to get all the
ancestors up to but not including the element matched by the selector. In simple words
we can say it returns all ancestor elements between two given elements in a DOM
hierarchy.
The following example will add a border around all the ancestor elements of
the <li> excluding <html> element i.e. add a border
to <ul>, <div> and <body> element.
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("li").parentsUntil("html").addClass("frame");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery Traversing Descendants
Traversing Down the DOM Tree
In logical relationships a descendant is a child, grandchild, great-grandchild, and so on.
jQuery provides the useful methods such as children() and find() that you can use to
traverse down in the DOM tree either single or multiple levels to easily find or get the
child or other descendants of an element in the hierarchy.
jQuery children() Method - The jQuery children() method is used to get the direct
children of the selected element. The following example will highlight the direct children
of the <ul> element which is <li> by adding the class .highlight on document ready.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul").children().addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery find() Method
The jQuery find() method is used to get the descendant elements of the selected element.
The find() and children() methods are similar, except that the find() method search
through multiple levels down the DOM tree to the last descendant, whereas
the children() method only search a single level down the DOM tree. The following
example will add a border around all the <li> elements that are descendants of
the <div> element.
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("div").find("li").addClass("frame");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
However, if you want to get all the descendant elements you can use the universal
selector.
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("div").find("*").addClass("frame");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery Traversing Siblings
Traversing Sideways in DOM Tree
In logical relationships siblings are those elements that share the same parent.
jQuery provides several methods such as siblings(), next(), nextAll(), nextUntil(), prev(),
prevAll() and prevUntil() that you can use to traverse sideways in the DOM tree.
jQuery siblings() Method - The jQuery siblings() method is used to get the sibling
elements of the selected element.
The following example will highlight the siblings of the <p> element which
are <h1> and <ul> by adding the class .highlight on document ready.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").siblings().addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
You can optionally include one or more selector as a parameter within
the siblings() method to filter your search for the siblings. The following example will
only apply the border around the siblings of the <p> that are <ul> elements.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").siblings("ul").addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery next() Method - The jQuery next() method is used to get the immediately
following sibling i.e. the next sibling element of the selected element. The following
example will highlight the next sibling of the <p> element which is the <ul> element.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").next().addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery nextAll() Method - The jQuery nextAll() method is used to get all following
siblings of the selected element. The following example will highlight all the siblings of
the <p> element that comes next to it.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").nextAll().addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery nextUntil() Method - The jQuery nextUntil() method is used to get all the
following siblings up to but not including the element matched by the selector. In simple
words we can say it returns all the next siblings elements between two given elements in
a DOM hierarchy.
The following example will highlight all the following sibling elements of
the <h1> element excluding the <ul> element i.e. highlight both the <p> element.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("h1").nextUntil("ul").addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery prev() Method - The jQuery prev() method is used to get the immediately
preceding sibling i.e. the previous sibling element of the selected element. The following
example will highlight the previous sibling of the <ul> element which is
the <p> element.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul").prev().addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery prevAll() Method - The jQuery prevAll() method is used to get all preceding
siblings of the selected element. The following example will highlight all siblings of
the <ul> element that comes prior to this.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul").prevAll().addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery prevUntil() Method - The jQuery prevUntil() method is used to get all the
preceding siblings up to but not including the element matched by the selector. In simple
words we can say it returns all the previous siblings elements between two given
elements in a DOM hierarchy.
The following example will highlight all the previous sibling elements of
the <ul> element excluding the <h1> element i.e. highlight both the <p> element.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul").prevUntil("h1").addClass("highlight");
});
</script>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
jQuery Filtering
Filtering the Elements Selection
jQuery provides several methods such as filter(), first(), last(), eq(), slice(), has(), not(),
etc. that you can use to narrow down the search for elements in a DOM tree.
jQuery first() Method - The jQuery first() method filters the set of matched elements
and returns the first element from the set. The following example will only highlight the
first <li> element within the <ul> element by adding the class .highlight on document
ready.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").first().addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Last list item</li>
</ul>
jQuery last() Method - The jQuery last() method filters the set of matched elements and
returns the last element from the set. The following example will only highlight the
last <li> element within the <ul> element by adding the class .highlight on document
ready.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").last().addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Last list item</li>
</ul>
jQuery eq() Method - The jQuery eq() method filters the set of matched elements and
returns only one element with a specified index number. The following example will
highlight the second <li> element within the <ul> element by adding the
class .highlight on document ready.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").eq(1).addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Last list item</li>
</ul>
Note: The index supplied to the eq() method indicates the 0-based position of the
element that means the index 0 target the first element, the index 1 targets the second
element and so on. Also this index refers to the position of the element within the jQuery
object, not within the DOM tree.
You can also specify a negative index number. A negative index number indicates a
position starting from the end of the set, rather than the beginning. For example, the eq(-
2) indicates the second last element within the set of matched elements.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").eq(-2).addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Fourth list item</li>
</ul>
jQuery filter() Method - The jQuery filter() method can take the selector or a function
as its argument to filters the set of matched elements based on a specific criteria.
The supplied selector or function to the filter() method is tested against each element in
the set of matched elements and all the elements that matching the supplied selector or
pass the function's test will be included in the result.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").filter(":even").addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Fourth list item</li>
</ul>
As stated earlier you can also pass a function to the filter() method to filter the set of
matched elements based on certain conditions. The following example will test
each <li> element within the <ul> and highlight those <li> elements whose indexes are
odd numbers i.e. highlights only second and fourth list item as the index is zero-based.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").filter(function(index){
return index % 2 !== 0;
}).addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Last list item</li>
</ul>
jQuery has() Method - The jQuery has() method filters the set of matched elements and
returns only those elements that has the specified descendant element. The following
example will highlight all the <li> elements that has the descendant <ul> elements.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").has("ul").addClass("highlight");
});
</script>
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>
<ul>
<li>Section 2.1</li>
<li>Section 2.2</li>
<li>Section 2.3</li>
</ul>
</li>
<li>Section 4</li>
</ul>
jQuery not() Method - The jQuery not() method filters the set of matched elements and
returns all elements that does not met the specified conditions. It can take the selector or
a function as its argument.
The supplied selector or function to the not() method is tested against each element in
the set of matched elements and all the elements that is not matching the supplied
selector or pass the function's test will be included in the result.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").not(":even").addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Fourth list item</li>
</ul>
The not() method can take a function as its argument in the same way that filter() does,
but it works just opposite of the filter() method i.e. the elements that pass the function's
test are excluded and rest the elements are included in the result.
The following example will test each <li> element within the <ul> and highlight
those <li> elements whose indexes are not the odd numbers i.e. highlights first and third
list item.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").not(function(index){
return index % 2 !== 0;
}).addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Fourth list item</li>
</ul>
jQuery slice() Method
The jQuery slice() method filters the set of matched elements specified by a range of
indices. This method accepts start and end (optional) index number as arguments, where
the start index specifies the position at which the elements begin to be selected and the
end index specify the position at which the elements stop being selected.
The following example will highlight the first and second <li> elements within
the <ul> element by adding the class .highlight on document ready.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").slice(0, 2).addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Fourth list item</li>
</ul>
You can also specify a negative index numbers. A negative index number indicates a
position starting from the end of the set, rather than the beginning. For example,
the slice(-2, -1) only highlight the third list item, since it is the only item in the range
between two from the end (-2) and one from the end (-1), as end position is not included
in result.
<style>
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("ul li").slice(-2, -1).addClass("highlight");
});
</script>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Fourth list item</li>
</ul>
jQuery Progress Bar
What is a Progress Bar?
A progress bar is a graphical control element used to visualize the progression of an
extended computer operation, such as a download, file transfer, or installation.
Sometimes, the graphic is accompanied by a textual representation of the progress in a
percent format.
jQuery Progress Bar - Here is the full source code of the progress bar. Let’s first write
the code and then understand the code.
<style>
body {
background-color: rgb(226, 225, 225);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}

.outerDiv {
margin: 20px auto;
padding: 0;
width: 800px;
height: 40px;
overflow: hidden;
background: #e5e5e5;
border-radius: 6px;
border: 2px solid #000;
}

.innerDiv {
padding: 10px 0;
height: 90%;
width: 0;
background: rgb(87, 181, 243);
text-align: center;
font-weight: 600;
color: #fff;
border-radius: 6px;
}

select {
padding: 5px 8px;
margin: 10px auto;
width: 130%;
border: none;
font-size: 20px;
width: 80px;
cursor: pointer;
font-style: italic;
}

label {
font-size: 24px;

input[type="button"] {
background-color: #234d69;
border: none;
color: #fff;
padding: 20px 35px;
margin: 10px;
text-align: center;
text-decoration: none;
display: block;
font-size: 24px;
font-weight: 600;
border-radius: 20px;
cursor: pointer;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0,
0, 0, 0.19)
}
</style>
<h1>jQuery Simple Progress Bar</h1>
<label for="percentage">Select Percentage :

<select id="percentage">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>
</label>

<div class="outerDiv">
<div class="innerDiv">
</div>
</div>
<input type="button" id="myButton" value="Start Animation" />
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
animateProgressBar($('#percentage').val());
});

function animateProgressBar(percentageCompleted) {
$('.innerDiv').animate({
'width': (800 * percentageCompleted) / 100
}, 1000);

$({ counter: 1 }).animate({ counter: percentageCompleted }, {


duration: 1000,
step: function () {
$('.innerDiv').text(Math.ceil(this.counter) + ' %');
}
})
}
});
</script>
Steps:
1. We have first built the UI portion of the progress bar using HTML & CSS
2. At first, we have made a function animateProgressBar() which is taking a parameter
“percentageCompleted” inside that we are increasing the width of innerDiv by
animate() method. Then we are using another animate() function in which we are
increasing the counter value from 1 to ‘percentageCompleted’ and in every step of the
animation we are changing the text of the innerDiv to the updated counter
3. On the click of the button, we are invoking the function animateProgressBar() with the
argument ‘value of the <select> element’
Now run the above code and you will get the following page in the browser.

Now select the percentage and click on the Start Animation button and you will get the
following output in the browser.
Optimize jQuery Progress Bar
Optimize jQuery Progress Bar with Example
In this article, I am going to discuss How to Optimize the jQuery Progress Bar with
Examples. Please read our previous article, where we discussed jQuery Progress Bar.
This is a continuation part to our previous article. So, please read our previous
article before proceeding to this article. At the end of this article, you will understand
how to make the progress bar more optimized and enhanced
Optimize jQuery Progress Bar
At the moment we have two problems with our progress bar program
1. When you select 40%, it starts to count from 1 to 40 which is good. Now if you select
80%, it starts again from 1 and counts all the way till 80, instead of continuing to
count from 40 to 80.
2. Again, if you want to go back from 80% to 50%, we expect that it will start from 80%
and will end at 50%. But instead of that, it starts again from 1 and counts till 50.
How to Solve the above two problems?
Now let’s solve these two problems. At first, let’s understand that why this is happening.
You can see that we have set the counter value 1 at the initial stage and we are running
that from 1 to the percentageCompleted. That is why it is always counting from that
percentage. Instead of that if we can keep track of the previous percentage value which
user selected then we can solve the problem. We will run the counter from the previous
percentage value to the current percentage value.
Notice that how we can implement that in our program
<style>
body {
background-color: rgb(226, 225, 225);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}

h1 {
font-size: 40px;
margin-bottom: 30px;
padding: 30px;
text-align: center;
text-transform: capitalize;
font-style: italic;
}

.outerDiv {
margin: 20px auto;
padding: 0;
width: 800px;
height: 40px;
overflow: hidden;
background: #e5e5e5;
border-radius: 6px;
border: 2px solid #000;
}

.innerDiv {
padding: 8px 0;
height: 90%;
width: 0;
background: rgb(87, 181, 243);
text-align: center;
font-size: 20px;
font-weight: 600;
color: #fff;
border-radius: 6px;
}

select {
padding: 5px 8px;
margin: 10px auto;
width: 130%;
border: none;
font-size: 20px;
width: 80px;
cursor: pointer;
font-style: italic;
}

label {
font-size: 24px;

input[type="button"] {
background-color: #234d69;
border: none;
color: #fff;
padding: 20px 35px;
margin: 10px;
text-align: center;
text-decoration: none;
display: block;
font-size: 24px;
font-weight: 600;
border-radius: 20px;
cursor: pointer;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0,
0, 0, 0.19)
}
</style>
<h1>jQuery Progress Bar</h1>
<label for="percentage">Select Percentage :

<select id="percentage">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>
</label>

<div class="outerDiv">
<div class="innerDiv">
</div>
</div>
<input type="button" id="myButton" value="Start Animation" />
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
var currentPercentage = 0;
var previousPercenage = 0;
$('#myButton').click(function () {
previousPercenage = currentPercentage;
currentPercentage = $('#percentage').val();
animateProgressBar(previousPercenage, currentPercentage);
});

function animateProgressBar(previousPercenage, currentPercentage) {


$('.innerDiv').animate({
'width': (800 * currentPercentage) / 100
}, 1000);

$({ counter: previousPercenage }).animate({ counter:


currentPercentage }, {
duration: 1000,
step: function () {
$('.innerDiv').text(Math.ceil(this.counter) + ' %');
}
})
}
});
</script>
Steps:
1. We have taken two parameters previousPercentage & currentPercentage. We are
setting currentPercentage to the value from the dropdown list and
previousPercentage to currentPercentage. Thus, we keep tracking what users
selected previously.
2. In the function animateProgressBar() instead of using one parameter, we are using
two parameters previousPercentage & currentPercentage and we are incrementing
the counter value from previousPercentage to currentPercentage.
Output: Now run the above code and you will get the following output.

Now select the percentage as 80 and click on the Start Animation button and this time it
will start from 40, not from 1 as expected and you will get the following output.
But, here, we have a problem, when it is on 80 select 50 and click the Start Animation
button and you will get the following output.

Observe, it stops at 51% instead of stopping at 50%. For this problem, we can modify our
code a little bit. Modify the script section as follows.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
var currentPercentage = 0;
var previousPercenage = 0;
$('#myButton').click(function () {
previousPercenage = currentPercentage;
currentPercentage = $('#percentage').val();
animateProgressBar(previousPercenage, currentPercentage);
});

function animateProgressBar(previousPercenage, currentPercentage) {


$('.innerDiv').animate({
'width': (800 * currentPercentage) / 100
}, 1000);
if (previousPercenage > currentPercentage) { currentPercentage =
currentPercentage - 1; }

$({ counter: previousPercenage }).animate({ counter: currentPercentage


}, {
duration: 1000,
step: function () {
$('.innerDiv').text(Math.ceil(this.counter) + ' %');
}
})
}
});
</script>
If the previousPercentage is greater than the currentPercentage then we are
decrementing the currentPercenatge by 1. And that solved our problem. Now, test this
and you will get the output as expected as shown in the below image.

But look at the amount of code we are writing. It can be much less with this following
piece of code. It will work exactly the same.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
animateProgressBar($('#percentage').val());
});

function animateProgressBar(currentPercentage) {
$(".innerDiv").animate({ "width": (currentPercentage * 800) / 100 }, {
duration: 1000,
step: function (now) {
$(".innerDiv").text(Math.ceil((now / 800) * 100) + ' %');
}
});
}
});
</script>
In this code, we have simplified all the things. You have known the step function of the
animate() method in previous articles. The step option of the animate function can be
used to define a function that gets called after each step of the animation. This method
has 2 parameters – now & tween.
1. now – contains the value being animated
2. tween – is a complex object and contains several properties. A few are listed below.
For the complete list set a breakpoint and inspect the object.
 elem – The DOM element being animated
 now – The value the animation is currently at
 end – The value the animation will end at
In this example, we are using the now parameter to keep track of the value that is being
currently animated. Using that now parameter we can convert to percentage and to set
the text of innerDiv.
In the next article, I am going to discuss how to toggle password visibility using the
show/hide password checkbox with Examples. Here, in this article, I try to explain how
to optimize the jQuery Progress Bar with Examples and I hope you enjoy this optimize
jQuery Progress Bar article.
jQuery Show Hide Password
jQuery Show Hide Password
In this article, I am going to discuss jQuery Show Hide Password with Examples.
Please read our previous article, where we discussed how to optimize the jQuery
Progress Bar. At the end of this article, you will learn how to toggle password visibility
using jQuery.
Example: One of the simplest ways of achieving this show/hide password is by changing
the type attribute of the password field depending on the checked status of the Show
password checkbox
1. If the Show password checkbox is CHECKED change the type to text
2. If the Show password checkbox is NOT CHECKED change the type to password
We have used the ternary operator to do so.
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="D:\MyWebsiteDocuments\JQuery\style.css">
<title>Login Page</title>
</head>
<body>
<section>
<div class="contentBox">
<div class="formBox">
<h2 class="login">Login</h2>
<form>
<div class="inputBox">
<input type="text" name="username" placeholder="User
Name" size="30">
</div>

<div class="inputBox">
<input type="password" id="txtPassword"
name="password" placeholder="Password">

</div>
<label for="showPassword"><input type="checkbox"
id="showPassword">Show Password</label>

<div class="inputBox">
<input id="login" type="submit" value="Log In">
</div>

<div class="remember">
<label for="remember"><input type="checkbox"
id="remember">Remember Me</label>
<a class="link" href="#">Forgot Password?</a>
</div>
</form>
</div>
<a href="#" id="create" class="link">Create an Account</a>
</div>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#showPassword').click(function () {
$('#txtPassword').attr('type', $(this).is(':checked') ?
'text' : 'password');
});
});
</script>
</body>
</html>
Style.css
@import url("https://fonts.googleapis.com/css2?
family=Poppins&display=swap");

* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
.contentBox {
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: space-around;
flex-direction: column;
}
.formBox {
margin: auto;
background-color: #bec2bf;
border-radius: 20px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 400px;
height: 350px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0,
0.23);
}
.login {
color: black;
font-size: 1.5em;
text-align: center;
margin-top: 20px auto;
padding-top: 20px;
}
.inputBox {
width: 100%;
margin: 20px auto;
}
.inputBox input {
width: 100%;
height: 40px;
margin: auto;
padding: 5px 20px;
font-size: 16px;
border-radius: 20px;
border: none;
outline: none;
}
input[type="checkbox"] {
width: 16px;
height: 16px;
margin-right: 5px;
}
#login {
background-color: #4478fc;
color: white;
border: none;
outline: none;
}
.remember {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 10px;
margin-bottom: 30px;
font-size: 16px;
}
form {
width: 80%;
}
.link {
color: #4478fc;
text-decoration: none;
}
#create {
transform: translateY(-130px);
}
Output:
Now run the above code and when the Show password checkbox is NOT CHECKED, the
password is masked as shown in the below image.

When the Show password checkbox is CHECKED, the password is in clear text and
visible to the user as shown in the below image.
The problem with the above approach is that it does not work in IE 8 and earlier versions.
This is because with IE8 and earlier versions the type attribute of input elements cannot
be changed once set. We can modify our code so that the following code works in all
browsers including IE8 and earlier versions.
When the Show password checkbox is clicked
1. Retrieve the value from the password textbox and store it in a variable for later use.
2. Delete the password input filed.
3. If the “Show password” checkbox is CHECKED, then add a new input field of type text,
else add a new input filed of password. In both cases set the value attribute of the input
element = the variable created in Step 1.
Please modify the example as shown below and it should work as expected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Login Page</title>
</head>
<body>
<section>
<div class="contentBox">
<div class="formBox">
<h2 class="login">Login</h2>
<form>
<div class="inputBox">
<input class="input" type="text" name="username"
placeholder="User Name" size="30">
</div>
<div class="inputBox">
<input class="input" type="password"
id="txtPassword" name="password" placeholder="Password">
</div>
<label for="showPassword"><input type="checkbox"
id="showPassword">Show Password</label>
<div class="inputBox">
<input id="login" type="submit" value="Log In"
class="input">
</div>
<div class=" remember">
<label for="remember"><input type="checkbox"
id="remember">Remember Me</label>
<a class="link" href="#">Forgot Password?</a>
</div>
</form>
</div>
<a href="#" id="create" class="link">Create an Account</a>
</div>
</section>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
$('#showPassword').click(function () {
var currentPasswordField = $('#txtPassword');
var currentPassword = currentPasswordField.val();
currentPasswordField.remove();

if ($(this).is(':checked')) {
$(this).before(`<input class="input" type="text"
id="txtPassword" value=${currentPassword} name="password"
placeholder="Password">`);
}
else {
$(this).before(`<input class="input" type="password"
id="txtPassword" value=${currentPassword} name="password"
placeholder="Password">`);
}
});
});
</script>
</body>
</html>
jQuery No-Conflict Mode
Using jQuery with Other JavaScript Libraries
As you already know, jQuery uses the dollar sign ($) as a shortcut or alias for jQuery.
Thus, if you use another JavaScript library that also uses the $ sign as a shortcut, along
with the jQuery library on the same page, conflicts could occur. Fortunately, jQuery
provides a special method named noConflict() to deal with such situation.
jQuery noConflict() Method - The jQuery.noConflict() method return the control of
the $ identifier back to other libraries. The jQuery code in the following example (line no-
10) will put the jQuery into no-conflict mode immediately after it is loaded onto the page
and assign a new variable name $j to replace the $ alias in order to avoid conflicts with
the prototype framework.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery noConflict() Demo</title>
<script src="js/prototype.js"></script>
<script src="js/jquery.js"></script>
<script>
// Defining the new alias for jQuery
var $j = jQuery.noConflict();
$j(document).ready(function(){
// Display an alert message when the element with ID foo is clicked
$j("#foo").click(function(){
alert("jQuery is working well with prototype.");
});
});

// Some prototype framework code


document.observe("dom:loaded", function(){
// Display an alert message when the element with ID bar is clicked
$("bar").observe("click", function(event){
alert("Prototype is working well with jQuery.");
});
});
</script>
</head>
<body>
<button type="button" id="foo">Run jQuery Code</button>
<button type="button" id="bar">Run Prototype Code</button>
</body>
</html>
Note: Many JavaScript libraries use the $ as a function or variable name, just like the
jQuery. Some of these libraries are: mootools, prototype, zepto etc.
However, if you don't want to define another shortcut for jQuery, may be because you
don't want to modify your existing jQuery code or you really like to use $ because it saves
time and easy to use, then you can adopt another quick approach — simply pass the $ as
an argument to your jQuery(document).ready() function, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery noConflict() Demo</title>
<script src="js/prototype.js"></script>
<script src="js/jquery.js"></script>
<script>
jQuery.noConflict();
jQuery(document).ready(function($){
// The dollar sign in here work as an alias to jQuery
$("#foo").click(function(){
alert("jQuery is working well with prototype.");
});
});

// Some prototype framework code


document.observe("dom:loaded", function(){
// The dollar sign in the global scope refer to prototype
$("bar").observe("click", function(event){
alert("Prototype is working well with jQuery.");
});
});
</script>
</head>
<body>
<button type="button" id="foo">Run jQuery Code</button>
<button type="button" id="bar">Run Prototype Code</button>
</body>
</html>
Including jQuery Before Other Libraries
The above solutions to avoid conflicts rely on jQuery is being loaded after prototype.js is
loaded. However, if you include jQuery before other libraries, you may use full
name jQuery in your jQuery code to avoid conflicts without calling
the jQuery.noConflict(). But in this scenario the $ will have the meaning defined in the
other library.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery noConflict() Demo</title>
<script src="js/jquery.js"></script>
<script src="js/prototype.js"></script>
<script>
jQuery(document).ready(function($){
// Use full jQuery function name to reference jQuery
jQuery("#foo").click(function(){
alert("jQuery is working well with prototype.");
});
});

// Some prototype framework code


document.observe("dom:loaded", function(){
// The dollar sign here will have the meaning defined in prototype
$("bar").observe("click", function(event){
alert("Prototype is working well with jQuery.");
});
});
</script>
</head>
<body>
<button type="button" id="foo">Run jQuery Code</button>
<button type="button" id="bar">Run Prototype Code</button>
</body>
</html>
AJAX & jQuery -Ajax Tutorial
AJAX
 is a web development technique for creating interactive web applications. If you know
JavaScript, HTML, CSS, and XML, then you need to spend just one hour to start with
AJAX.
 Asynchronous JavaScript and XML, while not a technology in itself, is a term coined in
2005 by Jesse James Garrett, that describes a “new” approach to using a number of
existing technologies together,
including HTML or XHTML, CSS, JavaScript, DOM, XML, and most importantly
the XMLHttpRequest object. When these technologies are combined in the Ajax
model, web applications are able to make quick, incremental updates to the user
interface without reloading the entire browser page. This makes the application faster
and more responsive to user actions.
 JavaScript includes features of sending asynchronous http request using
XMLHttpRequest object. Ajax is about using this ability of JavaScript to send
asynchronous http request and get the xml data as a response (also in other formats)
and update the part of a web page (using JavaScript) without reloading or refreshing
entire web page.
The following figure illustrates the Ajax functionality.

Why to Learn Ajax?


AJAX is a new technique for creating better, faster, and more interactive web
applications with the help of XML, HTML, CSS, and Java Script.
 Ajax uses XHTML for content .
 Ajax uses CSS for presentation .
 Ajax uses JavaScript along with Document Object Model for dynamic content display.
 Conventional web applications transmit information to and from the sever using
synchronous requests. It means you fill out a form, hit submit, and get directed to a
new page with new information from the server.
 With AJAX, when you hit submit, JavaScript will make a request to the server,
interpret the results, and update the current screen. In the purest sense, the user
would never know that anything was even transmitted to the server.
 XML is commonly used as the format for receiving server data, although any format,
including plain text, can be used.
 AJAX is a web browser technology independent of web server software.
 A user can continue to use the application while the client program requests
information from the server in the background.
 Natural user interaction. Clicking is not required, mouse movement is a sufficient
event trigger.
 Data-driven as opposed to page-driven.
AJAX is Based on Open Standards
AJAX is based on the following open standards:
 Browser-based presentation using HTML and Cascading Style Sheets (CSS).
 Data is stored in XML format and fetched from the server.
 Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
 JavaScript to make everything happen.
AJAX cannot work independently. It is used in combination with other technologies to
create interactive webpages.
* JavaScript
 Loosely typed scripting language.
 JavaScript function is called when an event occurs in a page.
 Glue for the whole AJAX operation.
* DOM
 API for accessing and manipulating structured documents.
 Represents the structure of XML and HTML documents.
* CSS
 Allows for a clear separation of the presentation style from the content and may be
changed programmatically by JavaScript
* XMLHttpRequest
 JavaScript object that performs asynchronous interaction with the server.
Sending an XMLHttpRequest
A common JavaScript syntax for using the XMLHttpRequest object looks much like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById(“demo”).innerHTML = xhttp.responseText;
}
};
xhttp.open(“GET”, “filename”, true);
xhttp.send();
Example Explained :
The first line in the example above creates an XMLHttpRequest object:
var xhttp = new XMLHttpRequest();
The onreadystatechange property specifies a function to be executed every time the
status of the XMLHttpRequest object changes:
xhttp.onreadystatechange = function()
When readyState property is 4 and the status property is 200, the response is ready:
if (this.readyState == 4 && this.status == 200)
The responseText property returns the server response as a text string.
The text string can be used to update a web page:
document.getElementById(“demo”).innerHTML = xhttp.responseText;
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.
Ready State :
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 readystatus
status :
100: "Continue"
200: "OK"
400: "Bad Request"
401: "Unauthorized"
403: "Forbidden"
404: "Page not found"
500: "Internal Server Error"
statusText :
Returns the status-text
 “OK”
 “Not Found”
The onreadystatechange function is called every time the readyState changes.
jQuery — Ajax
JQuery is a great tool which provides a rich set of AJAX methods to develop next
generation web application.
Advantages of jQuery Ajax
1. Cross-browser support
2. Simple methods to use
3. Ability to send GET and POST requests
4. Ability to Load JSON, XML, HTML or Scripts
Methods : The jQuery library includes various methods to send Ajax requests. These
methods internally use XMLHttpRequest object of JavaScript.
 ajax() : Sends asynchronous http request to the server .
 get() : Sends http GET request to load the data from the server .
 Post() : Sends http POST request to submit or load the data to the server.
 getJSON() : Sends http GET request to load JSON encoded data from the server.
 getScript() : Sends http GET request to load the JavaScript file from the server and
then executes it.
 load() : Sends http request to load the html or text content from the server and add
them to DOM element(s).
Let’s look at an overview of important jQuery Ajax methods in the next section.
jQuery ajax() Method
The jQuery ajax() method provides core functionality of Ajax in jQuery. It sends
asynchronous HTTP requests to the server.
Syntax: $.ajax(url);$.ajax(url,[options]);
Parameter description:
 url: A string URL to which you want to submit or retrieve the data
 options: Configuration options for Ajax request. An options parameter can be
specified using JSON format. This parameter is optional.
The following list all the options available for configuring Ajax request.
 accepts : The content type sent in the request header that tells the server what kind
of response it will accept in return.
 async : By default, all requests are sent asynchronously. Set it false to make it
synchronous.
 beforeSend : A callback function to be executed before Ajax request is sent.
 cache : A boolean indicating browser cache. Default is true.completeA callback
function to be executed when request finishes.
 contentType : A string containing a type of content when sending MIME content to
the server.Default is “application/x-www-form-urlencoded; charset=UTF-8”.
 crossDomain : A boolean value indicating whether a request is a cross-domain.
 data : A data to be sent to the server. It can be JSON object, string or array.
 dataType : The type of data that you’re expecting back from the server.
 error : A callback function to be executed when the request fails.
 global : A Boolean indicating whether to trigger a global Ajax request handler or not.
Default is true.
 headers : An object of additional header key/value pairs to send along with request.
 ifModified : Allow the request to be successful only if the response has changed since
the last request. This is done by checking the Last-Modified header. Default value is
false.
 isLocal : Allow the current environment to be recognized as local.
 jsonp : Override the callback function name in a JSONP request. This value will be
used instead of ‘callback’ in the ‘callback=?’ part of the query string in the url.
 jsonpCallback : String containing the callback function name for a JSONP request.
 mimeType : String containing a mime type to override the XMLHttpRequest mime
type.
 password : A password to be used with XMLHttpRequest in response to an HTTP
access authentication request.
 processData : A Boolean indicating whether data assigned to data option will be
converted to a query string. Default is true.
 statusCode : A JSON object containing numeric HTTP codes and functions to be
called when the response has the corresponding code.
 success : A callback function to be executed when Ajax request succeeds.
 timeout : A number value in milliseconds for the request timeout.
 type : A type of http request e.g. POST, PUT and GET. Default is GET.
 url : A string containing the URL to which the request is sent.
 username : A username to be used with XMLHttpRequest in response to an HTTP
access authentication request.
 xhr : A callback for creating the XMLHttpRequest object.
 xhrFields : An object of fieldName-fieldValue pairs to set on the native
XMLHttpRequest object.
Let’s see how to send http requests using $.ajax() (or jQuery.ajax()) method.
Send Ajax Request
The ajax() methods performs asynchronous http request and gets the data from the
server. The following example shows how to send a simple Ajax request.
Example: jQuery Ajax Request
$.ajax('/jquery/getdata', // request url
{
// success callback Function
success: function (data, status, xhr) {
$('div').append(data);
}
});<div></div>
In the above example, first parameter ‘/getData’ of ajax() method is a url from which we
want to retrieve the data.
The second parameter is options parameter in JSON format where we have specified
callback function that will be executed when request succeeds. You can configure other
options as mentioned in the above table.
The following example shows how to get the JSON data using ajax() method.
Example: Get JSON Data
$.ajax('/jquery/getjsondata',
{
dataType: 'json', // type of response data
timeout: 500, // timeout milliseconds
success: function (data,status,xhr) {
$('p').append(data.firstName + ' ' + data.middleName + ' ' +
data.lastName);
},
error: function (jqXhr, textStatus, errorMessage) {
$('div').append('Error: ' + errorMessage);
}
});<div></div>
In the above example, first parameter is a request url which will return JSON data. In the
options parameter, we have specified dataType and timeout options. The dataType option
specifies the type of response data, in this case it is JSON. The timeout parameter
specifies request timeout in milliseconds. We have also specified callback functions for
error and success.
The ajax() method returns an object of jQuery XMLHttpRequest. The following example
shows how to use jQuery XMLHttpRequest object.
Example: ajax() Method
var ajaxReq = $.ajax('GetJsonData', {
dataType: 'json',
timeout: 500
});ajaxReq.success(function (data, status, jqXhr) {
$('p').append(data.firstName + ' ' + data.middleName + ' ' +
data.lastName);
})

ajaxReq.error(function (jqXhr, textStatus, errorMessage) {


$('div').append('Error: ' + errorMessage);
})<div></div>
Send Http POST request using ajax()
The ajax() method can send all type of http requests. The following example sends http
POST request to the server.
Example: Send POST Request
$.ajax('/jquery/submitData', {
type: 'POST', // http method
data: { myData: 'This is my data.' }, // data to submit
success: function (data, status, xhr) {
$('p').append('status: ' + status + ', data: ' + data);
},
error: function (jqXhr, textStatus, errorMessage) {
$('div').append('Error' + errorMessage);
}
});
<div></div>
Query get() Method
The jQuery get() method sends asynchronous http GET request to the server and
retrieves the data.
Syntax: $.get(url, [data],[callback]);
Parameters Description:
 url: request url from which you want to retrieve the data
 data: data to be sent to the server with the request as a query string
 callback: function to be executed when request succeeds
The following example shows how to retrieve data from a text file.
Example: jQuery get() Method
$.get('/data.txt', // url
function (data, textStatus, jqXHR) { // success callback
alert('status: ' + textStatus + ', data:' + data);
});
jQuery post() Method
The jQuery post() method sends asynchronous http POST request to the server to submit
the data to the server and get the response.
Syntax: $.post(url,[data],[callback],[type]);
Parameter Description:
 url: request url from which you want to submit & retrieve the data.
 data: json data to be sent to the server with request as a form data.
 callback: function to be executed when request succeeds.
 type: data type of the response content.
Let’s see how to submit data and get the response using post() method. Consider the
following example.
Example: jQuery post() Method
$.post('/jquery/submitData', // url
{ myData: 'This is my data.' }, // data to be submit
function(data, status, jqXHR) {// success callback
$('p').append('status: ' + status + ', data: ' + data);
})<p></p>
jQuery load() Method
The jQuery load() method allows HTML or text content to be loaded from a server and
added into a DOM element.
Syntax: $.load(url,[data],[callback]);
Parameters Description:
 url: request url from which you want to retrieve the content
 data: JSON data to be sent with request to the server.
 callback: function to be executed when request succeeds
The following example shows how to load html content from the server and add it to div
element.
Example: Load HTML Content
$('#msgDiv').load('/demo.html');
<div id="msgDiv"></div>
In the above example, we have specified html file to load from the server and add its
content to the div element.
Note : If no element is matched by the selector then Ajax request will not be sent.
The load() method allows us to specify a portion of the response document to be inserted
into DOM element. This can be achieved using url parameter, by specifying selector with
url separated by one or multiple space characters as shown in the following example.
Example: jQuery load() Method
$('#msgDiv').load('/demo.html #myHtmlContent');<div id="msgDiv"></div>
In the above example, content of the element whose id is myHtmlContent, will be added
into msgDiv element.
Events : The jQuery library also includes following events which will be fired based on
the state of the Ajax request.
 ajaxComplete() : Register a handler function to be called when Ajax requests
complete.
 ajaxError(): Register a handler function to be called when Ajax requests complete
with an error.
 ajaxSend(): Register a handler function to be called before Ajax request is sent.
 ajaxStart(): Register a handler function to be called when the first Ajax request
begins.
 ajaxStop(): Register a handler function to be called when all the Ajax requests have
completed.
 ajaxSuccess(): Register a handler function to be called when Ajax request completes
successfully.
jQuery Interview Questions
What is jQuery?
jQuery is a JavaScript library that makes it easy to create dynamic web pages. It helps in
making web apps more efficient and interactive. It also helps to speed up the
development process by providing a set of functions that can be used to manipulate data.
It is a lightweight library that can be easily integrated into any website.
What is jQuery used for?
For building dynamic web pages, utilize JQuery. It can be applied to the development of
interactive websites that are simple to use and navigate. It also makes it easy to add
animations and transitions to your pages. With the help of jQuery, you can perform many
basic activities that would otherwise require numerous lines of JavaScript code by calling
methods instead.
Basic jQuery Interview Questions for Freshers
1. What are the advantages of jQuery?
 Most popular and open source
 Very fast and easily extensible
 Used to develop cross-browser compatible web applications as jQuery works in almost
the same manner for different kinds of browsers.
 Improves the performance of an application when using the minimised version of the
jQuery library. The size of the minimized js file is almost 50% less than the normal js
file. A reduction in the file size makes the web page load and work faster.
 Commonly implemented UI-related functionalities are written using minimal lines of
code.
2. How is jQuery different from other javascript frameworks?
There are a few differences between jQuery and other libraries. The following makes
jQuery lightweight and easier to understand, integrate, and use.
 jQuery is much smaller than other libraries.
 jQuery does not have any dependencies on other libraries or frameworks. (Like babel).
 jQuery is not as complex as other libraries. This makes it easier to use and
understand.
 jQuery is not as heavy as other frameworks, It only uses the predefined javascript to
make web apps interactive.
3. List some Features of jQuery.
jQuery includes the following features:
 DOM element choices utilizing the multi-browser open source selector engine Sizzle, a
jQuery project spin-off.
 DOM manipulation is based on CSS selectors that employ element names and
characteristics, such as id and class, as criteria to pick nodes in the DOM.
 Events
 Animations and effects.
 AJAX.
 Deferred and Promise objects are used to govern asynchronous processing.
 JSON parsing
 Extensibility through plugins
 Utilities such as feature detection
 Compatibility methods that are natively present in newer browsers but require
fallbacks for older ones, such as inArray() and each ().
 Support for many browsers (not cross-browser). jQuery 1.x and 2.x both support
"current-1 versions" (that is, the current stable version of the browser and the version
that came before it) of Firefox, Google Chrome, Safari, and Opera. Version 1.x also
works with Internet Explorer 6 and above. However, jQuery version 2.x abandoned
support for Internet Explorer 6-8 (which accounts for less than 2% of all browsers in
use) and now only supports IE 9 and subsequent versions.
4. Is jQuery a JavaScript or JSON library file?
jQuery is said to be a library of single JavaScript files which consists of DOM/CSS
manipulations, event effects or animations, AJAX functions and various commonly used
plugins.
5. Does jQuery work for both HTML and XML documents?
No. jQuery works only for HTML documents.
6. What is jQuery Mobile?
Query Mobile is a JavaScript library that enables developers to create mobile-first
applications. It is a lightweight framework that allows developers to create rich, touch-
first interfaces that are optimized for touch devices.
jQuery Mobile is a mobile-first JavaScript library that aims to provide a modern and easy-
to-use framework for developing mobile apps. It was originally developed by Facebook to
improve the performance of its iOS and Android apps. Since then, it has been adopted by
many other companies, including Google, Yahoo, and Mozilla.
When using jQuery Mobile, you can use the library to create a mobile-first app that is
faster and easier to maintain than traditional web apps. It also makes it easier to add new
features to your app without having to rewrite your code.
JQuery Mobile is built on top of the jQuery JavaScript library. It works by using the same
techniques that are used when you are developing a traditional web app. However,
instead of using JavaScript, jQuery Mobile uses HTML5 and CSS3 to create a modern and
easy-to-use framework for developing mobile apps.
7. What is the $() function in the jQuery library?
 The $() function is used to access the properties of elements in the DOM (Document
Object Model). $() is similar to javascript’s selector functions, but it is more powerful
and has more options.
 $() can be used to access attributes, classes, id, data-* attributes, and more.
 Example - Suppose you want to change the colour of all the heading1 (h1) to green,
then you can do this with the help of jQuery as -
$(document).ready(function() {
$("h1").css("background-color", "green");
});
8. Explain $(document).ready() function?
The $(document).ready() function is a jQuery extension that allows you to immediately
run code when the document is ready. It's most commonly used to initialize a new page
or to load scripts or styles into the document. However, it can also be used to load a
script or style into the document at any time.
The $(document).ready() function is useful for loading scripts or styles into the document
at any time. It's not useful for loading scripts or styles into the document when the
document is already loaded.
9. What is the exact difference between the methods onload() and
document.ready()?
The onload() and document.ready() methods are used to load and render the HTML
and JavaScript code that is needed to display the page. However, they are different
methods in that they use different approaches to loading the HTML and JavaScript code.
The exact differences are -
onload() document.ready()
The onload() method is used to load The document.ready() method is used to load the
the HTML code. JavaScript code.
The onload() method loads the The document.ready() method loads the
HTML code using a pre-compiled JavaScript code using a pre-compiled object that
object that is passed to the onload is passed to the document.ready event handler.
event handler

10. Describe jQuery Connect in brief. Also, list its uses.


JQuery connect is a JavaScript library that provides a declarative API for binding data to
elements. It allows you to specify the data source, the element that should be bound to
the data, and the callback function that will be invoked when the element is bound.
The most common use case for jQuery connect is binding data to an element using an
attribute or value. However, it can also be used to bind data to elements dynamically or
to bind data to an element based on a condition.
11. What are the jQuery functions used to provide effects?
Some of the methods are listed below which provide the effect:
1. toggle() :
 This function is used to check the visibility of selected elements
to toggle between hide() and show() for the selected elements where:
o show() is run when the element is hidden.
o hide() is run when the element is visible.
 Syntax: $(selector).toggle(speed, easing, callback)
2. slideDown() :
 This function is used to either check the visibility of selected elements or to show the
hidden elements. We can use this function on the following types of hidden elements:
o Elements that are hidden using jQuery methods.
o Elements that are hidden using display: none in the element’s CSS properties.
 Syntax: $(selector).slideDown( speed, easing, callback )
3. fadeOut():
 This function is used to change the level of opacity for element of choice from
visible to hidden. When used, the fadded element will not occupy any space in DOM.
 Syntax: $(selector).fadeOut( speed, easing, callback )
4. fadeToggle():
 This is used for toggling between the fadeIn() and fadeOut() methods.
o If elements are faded in state, fadeToggle() will fade out those elements.
o If elements are faded out, fadeToggle() will fade in those elements.
 Syntax: $(selector).fadeToggle(speed, easing, callback)
5. animate():
 The method performs custom animation of a set of CSS properties. This method
changes an element from one state to another with CSS styles.
 The CSS property value is changed gradually, to create an animated effect.
 Syntax: (selector).animate({styles},speed,easing,callback) where “styles” is a
required field that specifies one or more CSS properties/values to animate. The
properties need to be mentioned in camel casing style.
 The parameters “speed”, “easing” and “callback” in the syntaxes of the above
methods represent:
o speed: Optional parameter and used for specifying the speed of the effect. The
default value is 400 milliseconds. The possible value of speed are “slow”, “fast” or
some number in milliseconds.
o easing: Again optional parameter is used for specifying the speed of elements to
different types of animation. The default value is “swing”. The possible value of
easing are “swing” and “linear”.
o callback: Optional parameter. The callback function specified here is
executed after the effect method is completed.
12. What is the use of css() method in jQuery?
The css() method is used to change the style property of the selected element.
13. Which jquery method is used to hide selected elements?
 The hide() function in jQuery is used to try and hide the chosen element.
 For Example - Suppose we need to hide a division tag, that consists of id = “ib”.
Then the jQuery code will be - $(“#ib”).hide();
14. What are events in jQuery?
User actions on a webpage are called events and handling responses to those is called
event handling. jQuery provides simple methods for attaching event handlers to selected
elements. When an event occurs, the provided function is executed.
15. How to iterate/loop through all p elements in jquery.
$.each() is an object iterator tool provided by jQuery, as is.each(), a jQuery collection
iterator(). So for traversing all the p elements, the sample code is -
$("p").each(function() {
console.log( $(this).attr('id'));
});
16. What is the significance of jQuery.length?
jQuery.length property is used to count the number of the elements of the jQuery
object.
17. What is jQuery click event?
 jQuery click event happens when we click on an HTML element.
 jQuery provides a method click() method that aids to trigger the click event.
 For example, $(“p”).click() will trigger the click event whenever the elements with
paragraph tag are clicked on a browser page.
Syntax:
$(selector).click(function(){
//code that runs when the click event is triggered
});
18. What is the purpose of JQuery's delay() method? Can you use this for
different types of browsers like (Internet Explorer)?
The delay() method is used to set the delay between two events, such as a click or a
change in state. The delay can be set to a number of different values, including
milliseconds, seconds, and even hours. This can be useful when you want to wait for an
event to occur before doing something else.
For example - you could use a delay of 5 minutes to wait for a user to click on your
button before moving on to the next step in your workflow.
Although the delay() method is not available in all browsers. In order to use it in Internet
Explorer, you will need to add the following line of code:
window.addEventListener('click', function() { delay(5000); });
But the latest Microsoft browser (Microsoft Edge) that replaces the internet explorer has
support for the jQuery delay() method.
In addition, the delay() method is not available in some browsers, such as Firefox and
Safari. To work around this issue, you can use the setTimeout() method instead.
19. Can you explain about ajaxStart() functions?
The ajaxStart() event is a global event that occurs when an Ajax request begins,
assuming no other Ajax requests are presently active. The ajaxStart() event can also be
used to cancel a previously called Ajax callback or to start a new one.
For example, suppose you have an online shopping cart application that allows
customers to add items to their shopping cart when they are ready to checkout.
An ajaxStart() event could be used to trigger a shopping cart initialization routine when
the user first visits the application, or any time a new shopping cart is about to be
initialized.
Similarly, a shopping cart termination routine could be triggered when the user is
finished shopping, or whenever a shopping cart is no longer needed.
20. Can you explain about ajaxComplete() function?
The ajaxComplete() is called regardless of whether the request is successful or fails,
and a complete callback is returned, even for synchronous queries.
This is very useful for error handling. If a request fails but the result is not needed
immediately, it is transferred to a cache, and then called later. This is especially useful if
you want to keep track of failed requests and retry those that were not successful. A
typical scenario is the case of an AJAX request but no data is returned, or the data is
returned but not as intended. In this case, you can call ajaxComplete() to get a new set of
data and continue with your business logic. A successful AJAX request is not necessarily a
reason to call ajaxComplete(). you can still do other stuff while the data is being
transferred from the server to the browser. For example, you can scroll, pause the
video, or show a loading indicator.
21. Describe the benefits of jQuery Ajax techniques.
With the aid of DOM and JavaScript, There is a great advantage of AJAX. Ajax can request
and receive data from the server without requiring a page reload. jQuery Ajax methods
are a powerful way to make your web applications more responsive. They enable you to
take advantage of the power of Ajax by using JavaScript to make your web pages load
faster and more efficiently.
By using jQuery Ajax methods, you can take advantage of the power of Ajax by using
JavaScript to make your web pages load faster and more efficiently. The following
advantages of the AJAX Methods are -
 It allows us to eliminate the complete page reload and instead load only a portion of
the page.
 API that is simple.
 Cross-browser compatibility.
 POST and GET are supported.
 Upload a JSON, XML, HTML, or script file.
22. Can you tell something about jQuery each() method?
 The each() method in jQuery allows us to loop through different datasets such as
arrays or objects (even DOM objects).
 It can be used to loop through a number of DOM objects from the same selectors.
 For example, if you want to add a width=“600” to all the images in a page then we
select all images and loop through each of them and add width = "600" to each tag.
We can write the code as below:
$("img").each(function(im){
$(this).attr("width","600")
});
 $ is a jQuery object definer. In the above syntax, “this” is a DOM object and we can
apply jQuery functions to only jQuery objects which is why we convert the DOM object
to jQuery object by wrapping it inside the $ definer.
 We can also use each() to loop through the arrays of data and get the index and the
value of the position of data inside the array.
 For example,
var list = ["InterviewBit", "jQuery", "Questions"];
$.each(list, function(index, value){
console.log(index + " "+ value);
})
 The above code prints
0 InterviewBit
1 jQuery
2 Questions
 You can also use each() to loop through objects.
 For example:
var obj = {"name":"InterviewBit","type": "jQuery"};
$.each(obj, function(key,value){
console.log(key + " - " + value);
})
 The above code prints:
name - InterviewBit
type - jQuery
23. What is CDN?
CDN is an acronym that stands for Content Delivery Network or Content Distribution
Network. It is a big distributed system of servers spread throughout the internet in many
data centres. It downloads content from servers at a greater bandwidth, resulting in
speedier loading times. Several firms offer free public CDNs, including Google, Amazon,
Microsoft, Yahoo, etc.
24. What is the difference between javascript and jquery?
 JavaScript is an interpreted language written in C and is a combination of
ECMAScript and DOM whereas jQuery is a JavaScript library developed to run things
faster and make things simplified for JavaScript. jQuery doesn't have the ECMAScript.
 JavaScript requires long lines of code to code a functionality whereas in the case of
jQuery, just import the library and call the functions which would reduce the
programmer’s effort in coding.
 JavaScript doesn't have cross-browser compatible functionality which is why a
developer has to write code manually to implement the functionality. Whereas the
cross-browser code compatibility is inbuilt in jQuery.
25. In jQuery, what is the difference between the $(window).load and $
(document).ready functions?
$(window).load $(document).ready
$(window).load is an event that occurs The ready() method is typically the ideal
when the DOM and another page's location to write JavaScript code
contents are fully loaded. This event
occurs following the ready event. In
most circumstances, the script may be
run as soon as the DOM has finished
loading.
However, there may be times when you When a function needs to be made available
need to write scripts in the load() after the document has loaded, use the
method. For instance, to determine the ready() method. Whatever code you include
true width and height of a picture. in the $(document).ready() method will be
executed once the DOM of the page is
Once the DOM, CSS, pictures, and
prepared to run JavaScript code.
frames are entirely loaded, the $
(window).load event is called. As a
result, it is the optimal area to write
jQuery code to determine the real
picture size or to obtain information
about anything.

26. What exactly is a jQuery Data Table plug-in? Also, explain the uses with
examples.
A data table plug-in is a jQuery plugin that can be used to create custom tables. It allows
you to create a table with a custom layout, without having to write any code. It can be
used to create tables with different layouts, or even to create tables with custom
columns. The data table plug-in is a great way to add extra functionality to your websites,
especially if you want to add a table to your website that is not included in the default
layout.
Some of the uses for data tables are listed below -
 Data tables are great for displaying a lot of data at once. For example, you could
display a list of products on your website. You could also display the same data in a
table in your blog.
 Data tables are also great for displaying information that you want your visitors to
see. For example, you could display a list of products that you're selling on your
website. You could also display the same information in a table in your blog.
 Data tables are great for showing a lot of information in one place. For example, you
could display a list. of products on your website and then add additional information
about each product in the table.
27. What is the purpose of JQuery's serialize() method?
The serialize() method is a utility method of the jQuery library that allows you to serialize
data from a DOM element and return it in a format that can be used by other libraries.
This is useful when you want to pass data between different libraries or frameworks, or if
you want to create a custom API that can be used by other developers. For example - if
you want to pass JSON data from your application to a third-party API, you can use the
serialize() method to serialize the data and then pass it to the API. This way, the API
knows how to handle the data, and you don't have to worry about the format of the data.
The serialize() method is also useful when you need to send data between different
browsers. For example - if you want to send JSON data from one browser to another,
you can use the serialize() method to serialize the data and then send it using a custom
HTTP request.
If you're not sure what data you need to serialize, there's an easy way to find out: Just
type "serialize" into the console. You'll see a list of all the methods that are available on
your element. ul> li>serialize/li> li>unserialize/li> /ul> div id="example"> ul>
li>serialize/li> li>unserialize/li> /ul> /div>
28. What are the selectors in jQuery? How many types of selectors in jQuery?
In order to work with any element on the web page, we would first need to find it.
Selectors find the HTML elements in jQuery. Some of the most commonly used and basic
selectors are:
 Name: Used to select all elements which match the given element Name.
 #ID: Used to select a single element which matches with the given ID
 .Class: Used to select all elements which match with the given Class.
 Universal (*): Used to select all elements available in a DOM.
 Multiple Elements E, F, G: Used to select the combined results of all the specified
selectors E, F or G.
 Attribute Selector: Used to select elements based on their attribute value.
29. Explain how CSS classes can be manipulated in HTML using jQuery.
Query provides several methods to manipulate the CSS classes assigned to HTML
elements. The most important methods are addClass(), removeClass() and toggleClass().
 addClass(): This method adds one or more classes to the selected elements.
o Syntax: $(selector).addClass(className);
o You can also add multiple classes to the selector. Syntax:$
(selector).addClass(class1, class2);
 removeClass(): Similar to adding class, you can also remove the classes from the
elements by using this method.
o The removeClass() method can remove a single class, multiple classes, or all
classes at once from the selected elements.
o Syntax:
 For removing one class: $(selector).removeClass(class1);
 For removing multiple class: $(selector).removeClass(class1, class2, class 3);
 For removing all classes at once: $(selector).removeClass()
 toggleClass(): This method is used for adding or removing one or more classes from
the selected elements in such a way that if the selected element already has the class,
then it is removed. Else if an element does not have the specified class, then it is
added i.e. it toggles the application of classes.
o Syntax: $(selector).toggleClass(className);
30. State some different types of jQuery Methods.
jQuery provides a variety of methods for doing various tasks, such as manipulating the
DOM, events, and ajax. The table below covers many technique categories.
Essential Methods Characterization Classificatio
n
after(), append(), attr(), These methods alter DOM elements DOM
before(), etc. in some way, such as modifying Manipulation
attributes, style attributes, adding
and deleting elements, and so on.
addClass(), CSS(), hasClass(), These methods retrieve and set CSS CSS
removeClass(), toggleClass(), attributes of elements.
etc.
attr(), html(), These methods retrieve and set Attributes
HTMLremoveAttr(), prop(), element DOM properties.
val(), etc.
bind(), blur(), change(), These methods deal with DOM or Events
click(), focus(), keyup(), JavaScript events.
keydown(), etc.
animate(), fadeIn(), fadeOut(), These techniques are used to Effects
hide(), show(), stop(), etc. provide elements of animation.
get(), getJson(), post(), load(), These techniques provide Ajax AJAX
etc. functionality with jQuery.
children(), closest(), each(), These methods assist in traversing Traversing
first(), next(), filter(), from one DOM element to another
in a parent-child hierarchy, such as
parent(), siblings(), etc.
locating ancestors, descendants, or
sister elements of a specific
element.
blur(), change(), val(), Forms and their many components Forms
submit(), etc. are handled by these methods and
event handlers.
inArray(), isArray(), Utility methods are useful for Utilities
isFunction(), isNumeric(), obtaining information about various
isWindow(), isXmlDoc(), etc. objects, such as a browser, function,
array, or window.

31. Explain jQuery no-conflict.


jQuery no-conflict is a jQuery option that allows you to avoid conflicts between various
javascript frameworks or libraries. When you utilize jQuery's no-conflict mode, you
substitute the $ variable with a new variable and assign jQuery to other JavaScript
libraries. In addition, the $ symbol is utilized as a function or variable name in jQuery.
When no conflict is enabled, the $ symbol in jQuery becomes the global function name
and not the library name. For example, you may use the $ function to access other
libraries' data, but not their code. You can also use this option to avoid conflicts between
various jQuery plugins.
32. In jQuery, distinguish between the bind(), live(), and delegate() functions.
The bind() function does not connect events to items added after loading the DOM. In
contrast, the live() and delegate() methods also attach events to future items.
The distinction between live() and delegate() methods is that live() does not support
chaining. It will only function on a selection or an element. However,
the delegate() function supports chaining.
The bind() method works only within a dom element. If you want to bind events to items
in a different element, you can use the delegate() function. The bind() method is not
recommended for use in JavaScript. It is a best practice to call event handlers on items as
they are added to the DOM. The bind() method is only used to control the order in which
items are displayed. If you need to add items to a different order, you can use
the delegate() function. The bind() method is not intended to be used in a production
environment. It does not offer the same performance benefits as the delegate() method.
For Example - Consider the below code -
$(document).ready(function(){
$("#interviewbit").find("p").live("click", function(){
alert("Welcome to InterviewBit jQuery Interview Questions");
});
});
The live() method does not work in the given code, but we can easily do this
using the delegate() function. So the code will be like this -
$(document).ready(function(){
$(".interviewbit")children("p").delegate("a","click", function(){
alert("you clicked on a link to jQuery interview questions.");
});
});
jQuery Interview Questions for Experienced
1. Explain the operation of the jQuery connect() method.
 The connect() method of jQuery is a utility function that allows you to create a new
jQuery object and pass it to the jQuery object's constructor. This allows you to create
a new object with the same functionality as the original object, but without having to
manually set up the object's properties. For example, you can pass in an existing
jQuery object and it will be automatically set up to use the same properties as the
original object.
 When using connect() method, you can pass in a callback function that will be called
when the new object is ready. The callback function can be used to perform any
additional setup that needs to be done before the new object can be used.
 For example - you can set up a data source using the data() method of jQuery. When
using connect() method, you can pass in a callback function that will be called when
the new object is ready.
2. Distinguish between jquery.min.js and jquery.js.
The functionality of jquery.min.js and jquery.js is the same. However, If you are serving a
page that contains a lot of JavaScript, it is a good idea to minify it. Minifying
JavaScript (jquery.min.js) reduces the size of your file and makes it faster to load on all
platforms. Minifying your code also reduces the chances that erroneous code will be
rendered as a malicious attack because it makes it more difficult to test. With minified
JavaScript, you will get better page performance, faster loading, and shorter wait times
for your visitors.
There are also some of the major advantages of the jquery.min.js. -
 When JS files are minified in a production environment, they load faster and provide
faster and better page performance.
 Minifying a script also reduces the size of the file in the server’s temporary directory
and browser cache, which results in a faster download and a smaller server response.
 Another advantage of using minified JS is that it removes the need to include any
external JS files in the HTML document. This makes it easier to structure the code and
easier to edit the code.
3. Explain the benefits of using a CDN for the jQuery files.
Hosting jQuery on a Content Delivery Network (CDN) improves availability and
performance at a reduced cost and with less network traffic, improves latency (the time it
takes to send and receive a data packet from the server), and provides a device-specific
version of the contents.
CDNs are a great way to host your JavaScript and CSS files. By caching these files, you
can reduce the amount of time it takes for your site to load, making it faster and more
responsive. This is especially important for sites that serve large amounts of content,
such as blogs or e-commerce sites. By using a CDN, you can also reduce the number of
load times that occur when visitors access your site. In addition, by hosting your
JavaScript and CSS files on a CDN, you can also reduce the amount of bandwidth that is
consumed by your site.
Example - It makes it simple to maintain responsiveness for mobile screen sizes, as well
as safe storage space for important data or files.
Caching JavaScript and CSS files on a CDN is an important optimization that should be
considered when building a site with a lot of JavaScript and CSS files.
4. In jQuery, what is the difference between $(this) and this.
 $(this) is a jQuery object, whereas this is a JavaScript global object reference. We
may refer to DOM elements in HTML documents using this.
 $(this) refers to the parent object, whereas this is a DOM element that, in the case of
an array, represents an object with the .each() method, which shows the current
iteration.
We use this as an alternative to this.parent() to refer to the parent object in JavaScript.
This is more convenient than using this.parent(). We can also use this to refer to other
elements in HTML, as in an ul element:
var myElement = $('ul').each(function() {
var childElement = this.parent().nextSibling();
});
This is useful when you need to iterate over a list of elements and their children, but you
do not want to reference the parent object.
5. Can you describe the various methods for extracting a query text using regular
expressions?
There are two methods for obtaining a query string using regular expressions.
 String-based approach: This method aids in the generation of Strings by comparing
similar regular expressions using the.replace() function.
 Regular Express Based Approach: When compared to strings in JavaScript,
the regular expression technique is the most powerful method for extracting a
query string and pattern. Using the.exec() and.test() methods to compare against
patterns. Other String methods include match(), matchAll(), replace(), search(), and
split().
6. Explain the use of event.preventDefault() method.
Event.PreventDefault is a jQuery event that stops an event from firing when the user
clicks on a link or other trigger. It basically stops the default behaviour of the triggers
and allows any other event to occur. It is useful for preventing unwanted events from
firing when a user clicks on a link or other trigger. This can be useful when you want to
prevent users from accidentally clicking on links that open up new windows or tabs.
When you use an event like click or keypress, you can prevent the event from firing by
adding the event.preventDefault() method to the event object. When you
use event.preventDefault(), the event will not fire unless the user clicks on a link or
other trigger.
Event.preventDefault() is only available in jQuery 1.7 and later versions of jQuery.
Example - Assume you're developing an AJAX-based application in which you need to
submit form data through AJAX when a button in the form is clicked. So, if you click on a
button without preventing it, the button behaves normally and the website reloads. As a
result, the other event will not occur when you click the button. So, if we use prevent
default there, we can skip the button's default behaviour and instead perform the AJAX
event and alter the HTML DOM accordingly.
7. What Are the Benefits of Using Jquery Instead of Javascript in an Asp.net Web
Application?
Below are some of the benefits of using jQuery instead of javascript in ASP.net Web
Application -
 Jquery is well-written optimized javascript code, thus it will execute quicker until we
create the same standard optimized javascript code.
 Jquery is javascript code that is succinct, which implies that it requires the least
amount of code to do the same functionality as javascript.
 Jquery makes Javascript development faster since much of the functionality is already
provided in the library and we only need to access it.
 Because Jquery supports cross-browser compatibility, we save time on supporting all
browsers.
8. What is event.stopPropagation()?
event.stopPropagation() stops the event from propagating up the DOM tree,
preventing any parent handlers from being notified of the event. For example, if a link
with a click method is linked inside of a DIV or FORM that also has a click method
attached, the DIV or FORM click method will not fire.
9. Is it possible to pause or postpone the execution of the document.ready for a
period of time?
Yes, that is possible. With the release of jQuery 1.6, a new method called
"jQuery.holdReady(hold)" was added. This function allows you to postpone the execution
of the document.ready() event. The document.ready() event is triggered as soon as your
DOM is ready, however, there may be occasions when you wish to load extra JavaScript
or plugins that you have referenced.
10. Would you still favor jQuery in a case when things can be done simply using
javascript?
No. If we can accomplish our goals using simple JavaScript, then we should avoid using
jQuery. It is because the jQuery library is always xx kilobytes in size, thus there is no use
in wasting bandwidth. And because jQuery is built on top of javascript, it has numerous
functions that are more complicated than the simple job you can accomplish with
javascript. jQuery will also load all dependencies. It will have some speed issues as
compared to the javascript code.
jQuery Coding Questions
1. How to perform jQuery AJAX requests?
 jQuery provides the ajax() method to perform an AJAX (asynchronous HTTP) request.
 Syntax: $.ajax({name:value, name:value, ... }). The parameters specify one or more
values of name-value pairs.
o url: this name specifies the URL to send the request to. Default is the current
page.
o success(result,status,xhr): success callback function which runs when the
request succeeds
o error(xhr,status,error): A function to run if the request fails.
o async: Boolean value that indicates whether the request should be handled
asynchronous or not. The default value is true.
o complete(xhr,status): A function to run when the request is completed (after
success and error functions are handled)
o xhr: A function used for creating the XMLHttpRequest object
 Example:
$.ajax({
url: "resourceURL",
async: false,
success: function(result){
$("div").html(result);
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
2. What does the following code do?
$( "div#firstDiv, div.firstDiv, ol#items > [name$='firstDiv']" )
 The given code is an example of getting elements that satisfy multiple selectors at
once. The function returns a jQuery object having the results of the query.
 The given code does a query to retrieve those <div> element with the id
value firstDiv along with all <div> elements that has the class value firstDiv and all
elements that are children of the <ol id="items"> element and whose name attribute
ends with the string firstDiv.
3. Write a jQuery code to create and delete cookies from the browser.
There is no direct way to access the cookies using jquery. We can easily do this with the
help of pure javascript. To work with cookies in jQuery, you must install the Dough cookie
plugin or any other cookies plugins. The dough is simple to use and offers a number of
useful capabilities.
 Creating a cookies - $.dough("cookieName", "cookieValue");
 Reading a cookies - $.dough("cookieName");
 Deleting a cookies - $.dough("cookieName", "remove");
4. Consider the following code that exists in following HTML with the CSS:
<div id="expand"></div>
<style>
div#expand{
width: 50px;
height: 50px;
background-color: gray;
}
</style>
Write jQuery code to animate the #expand div, expanding it from 50 * 50 pixels to 300 *
300 pixels within five seconds.
We can do this by using the animate() function. We first need to have access to the div
element which has id value of expand and then apply animate function on the element as
follows:
$("#expand").animate(
{
width: "300px",
height: "300px",
},
5000
);
5. What does the following code do?
$( "div" ).css( "width", "500px" )
.add( "p" )
.css( "background-color", "yellow" );
 The given code first selects all the <div> elements and applies width of 500px to them
and adds all the <p> elements to the elements selection after which the code can
finally change the background color to yellow for all the <div> and <p> elements
 The given code is an example of method chaining in jQuery which is used to
accomplish a couple of things in one single instruction.
6. Can you explain the difference between jQuery.get() and jQuery.ajax()?
 jQuery.ajax() allows the creation of highly-customized AJAX requests, with options for
how long to wait for a response, what to do once the request is successful, how to
handle a failure scenarios, whether the request to be sent is blocking (synchronous) or
non-blocking (asynchronous), what format to expect as the response, and many more
customizable options.
 jQuery.get() is uses jQuery.ajax() underneath to create an AJAX request typically
meant for simple retrieval of information.
o There are various other pre-built AJAX requests given by jQuery such as:
 jQuery.post() for performing post requests
 jQuery.getScript() meant for loading and then executing a JavaScript file from
the server using GET request.
 jQuery.getJSON() for loading JSON-encoded data from the server using a GET
HTTP request.
7. Write a code snippet for preventing the default behavior of the submit button
for performing another event.
<script>
$(document).ready(function(){
$("#submitButton").click(function(event){
event.preventDefault();
});
});
</script>
8. Which of the two lines of code below is more efficient and why?
document.getElementById("interviewBit"); OR $("#interviewBit");
 The code document.getElementById( "interviewBit" ); is more efficient because its the
pure JavaScript version.
 The reason being jQuery is built on top of JavaScript and internally uses its methods
to make DOM manipulation easier. This introduces some performance overhead. We
need to remember that jQuery is not always better than pure JavaScript and we need
to use it only if it adds advantage to our project.
9. How do you disable elements in Jquery Using "attr"?
$('class_or_id_of_element_to_disable').attr('disabled', true);
$('class_or_id_of_element_to_disable').attr('disabled', false);
10. Can you write a jQuery code selector that needs to be used for querying all
elements whose ID ends with string “IB”?
We can use the following selector:
$("[id$='IB']")
11. Explain the .promise() method in jQuery.
 The .promise() method returns a dynamically generated promise that is resolved
when all actions of a certain type bound to the collection, queued or not, have
ended.
 The method takes two optional arguments:
o type - The default type is “fx” which indicates that the returned promise is
resolved only when all animations of the selected elements have been completed.
o target - If a target object is specified, .promise() will attach to promise to that
specified object and then return it rather than creating a new one.
12. Write A Jquery Code Snippet To Sort A String Array?
$(document).ready(function(){
var arr = [ "jQuery","Interview","Questions","By","InterviewBit"];
sortedArr = arr.sort();
$("#elementId").html(sortedArr.join(""));
});
The Output will be
["By","InterviewBit","Interview","jQuery","Questions"]
13. Consider the below code snippet and assume that there are 5 <div> elements
on the page. What is the difference between the start and end times displayed?
function getMinsSeconds() {
var dt = new Date();
return dt.getMinutes()+":"+dt.getSeconds();
}

$( "input" ).on( "click", function() {


$( "p" ).append( "Start: " + getMinsSeconds() + "<br />" );
$( "div" ).each(function( i ) {
$( this ).fadeOut( 1000 * ( i * 2 ) );
});
$( "div" ).promise().done(function() {
$( "p" ).append( "End: " + getMinsSeconds() + "<br />" );
});
});
 For the above code, the difference between the start and end times will be 10
seconds.
 This is because .promise() will wait for all <div> animations (here, all fadeOut() calls)
to complete, the last one will complete 10 seconds (i.e. 5 * 2 = 10 seconds) after
the fadeOut() starts.
14. Can you provide an example of chaining using a code snippet?
Old Code:
$(document).ready(function(){
$('#id').addClass('ib);
$('#id').css('color', 'blue);
$('#id').fadeIn('slow');
});
New Code after Chaining:
$(document).ready(function(){
$('#id').addClass('ib)
.css('color', 'blue')
.fadeIn('slow);
});
15. Can you tell the difference between prop() and attr()s?
 Both prop() and attr() can be used to get or set the value of the specified property of
an element attribute.
 The attr() gives the default value of a property whereas prop() returns its current
value.
Q #3) Explain the various jQuery effects method.
Answer: jQuery effects method help us to add some special effects to HTML elements
present in DOM of web pages, and these methods can be grouped in fade, slide, hide,
show and special effects.
The list of jQuery effects methods is given below.
 show(): This method can display /show the selected element.
 hide(): This method hides the element selected.
 toggle(): This method helps to toggle between show() and hide() method for the
selected element.
 fadeIn(): This method helps hidden elements in the page to fade in (displayed), i.e.
make hidden elements into an opaque element.
 fadeOut(): This method helps to hide an element from the web page by making the
colored element transparent, in other words, it fades out.
 fadeToggle(): This method helps to modify the state of the selected element, i.e.
hidden selected element into visible and visible selected element into the hidden
element.
 slideUp(): This method can help selected HTML element slide upward.
 slideDown(): This method can help selected HTML element slide downward.
 slideToggle(): This method helps to modify the position of the selected element, i.e.
selected element if slide upwards from its position, then it will slide down, and if the
selected element slid downwards from its position, then it will slide up.
 animate(): This method can change selected elements from one state to another with
CSS styles. The CSS property value such as position, color or shape changes within a
particular interval resulting in an animated effect.
Q #4) Give some examples of Ajax methods in jQuery.
Answer: Ajax helps to send and retrieve data as well as change the content of the web
page from a server without any need for the entire page reload. jQuery Ajax methods
such as load(), get(), post() facilitate Ajax calls made by the application.
Q #5) Explain the functionality of the Ajax() method.
Answer: Ajax() method sends asynchronous HTTP requests to the server and receives
the data from the server. Ajax() method is valuable as it offers the ability to specify both
success and failure callbacks.
Q #6) Explain the functionality of ajax load() method.
Answer: The load() method sends HTTP requests to load data in the form of HTML or
text content from a server and puts the returned data into the selected DOM element(s).
Q #7) Elaborate jQuery Ajax Events.
Answer: Ajax methods trigger an event handler that results in jQuery Ajax Events. Some
of the examples of jQuery Ajax Events are as listed below.
These events are categorized into local events and global events.
1. ajaxStart(): It is a Global Event, This event triggers as a result of starting of an Ajax
request, provided no other Ajax request currently running.
2. beforeSend(): It is a Local Event, as the name indicates, this event gets invoked
before Ajax request starts, thereby allowing to modify XMLHttpRequest objects.
3. ajaxSend(): It is a Global Event, and this event gets called before the Ajax request is
run.
4. success(): It is a Local Event. This event triggers only if the Ajax request was
successfully sent ( i.e. while sending Ajax request, the event does not display any
error from the server or from data).
5. ajaxSuccess(): It is a Global Event, triggers only if the request sent was successful.
6. error(): It is a Local Event, that gets triggered if an error occurs while executing the
request. (You can have either error or a success callback while sending Ajax request)
7. ajaxError(): It is a Global Event, which behaves the same as its local counterpart
error() event.
8. complete(): It is a Local Event. This event gets called regardless of the request being
successful or result in an error, and complete callbacks are received, even for
synchronous requests.
9. ajaxComplete(): It is a Global Event, which behaves the same as its local counterpart
complete() event, even for synchronous requests.
10.ajaxStop(): It is a Global Event, that gets triggered when no Ajax requests are still
being processed/ pending for processing.
Q #8) Explain the functionality of ajaxComplete() method.
Answer: The ajaxComplete() gets called regardless of the request being successful or
resulting in an error, and a complete callback is received, even for synchronous requests.
Q #9) Explain the functionality of ajaxStart() method.
Answer: The ajaxStart() event is a global event that triggers as a result of the Starting of
an Ajax request, provided no other Ajax requests are currently running.
Q #10) Explain some examples of Events in jQuery.
Answer: Actions on HTML elements across web pages are events in jQuery or JavaScript,
thereby making dynamic web pages.
Few examples of events are listed below.
 Clicking mouse over an element such as a button.
 Sending input element values from the HTML form.
 Reset of form element to their default values or reloading a page.
 Pressing or typing any one or more than one key on the keyboard.
 Scrolling of the web page etc.
Q #11) Explain examples of some of the categories of jQuery events.
Answer: jQuery events are categorized on the basis of their types:
 Mouse Events such as click & dblclick.
 Keyboard Events such as keyup & keydown.
 Form Events such as submit, focus & change.
 Document/Window Events such as load, unload & scroll.
Q #12) Explain the functionality of the jQuery CSS() method.
Answer: CSS() method in jQuery is used to check the present value of the style property,
add or change the style property of the selected element. In other words, the jQuery
CSS() method is used to GET and SET the DOM element’s CSS style properties.
Q #13) Differentiate between find() and children() methods.
Answer: .find() and .children() are used to locate child of the matched DOM
elements, .find() travels to any level down, whereas .children() travels a single level down
to locate the element.
Let’s consider the following DOM structure in an HTML document.

Syntax in jQuery .find() API to locate element within <li> tag with class “item-ii”.
$("li.item-li").find("li").css("background-color","yellow");
The result of the above method call is a yellow background on items A, B, 1, 2, 3
and C as shown in the below image.

.find() method selects all child elements of the DOM element being traversed.
Syntax in jQuery .children() API to locate element with <ul> tag with class
“level-2”.
$( "ul.level-2" ).children().css( "background-color", "yellow" );
The result of the above method call is a yellow background on items A, B, and C
as shown in the image below.
.children() method selects single level elements of the DOM element being traversed.
Q #14) Explain various types of selectors and their functionality in jQuery.
Answer: jQuery selectors are used to locate/select HTML elements from the DOM
hierarchy based on their attributes as listed below.
 name
 id
 class
 type
 values
Basic Selector Types are:
 Name
 ID
 Class Name
 Universal selector such as *, which selects all elements in a DOM.
 Multiple elements. Example: <li>, <p>, <span>.
 Attribute selector, Example: identify/select elements based on their attributes like
color, font style or background color.
Example, of Multiple elements and Attribute selectors in jQuery, is explained
below.

In the above jQuery code, the class attribute is a selector and the font color of the text
inside the HTML tag element is changed to green. This code will affect/change the font
color of texts inside all those elements that have class attributes.
Q #15) Differentiate between the ID and Class selector in jQuery.
Answer: Each HTML element can have only one ID, in other words, an element can be
identified with a unique ID, whereas you can use the same class on multiple elements.
Example of ID selector in jQuery in order to hide a DOM element with an ID as its
attribute, say <div> element with an ID as “gold_coin”
$('#gold_coin').hide();
If you want to hide, say all links having its class as “raw”,
$('a.raw').hide();
Q #16) Explain the advantages of jQuery Ajax methods.
Answer: Ajax can request and receive data from the server without page reload with the
help of DOM and JavaScript.
Advantages of using Ajax methods in jQuery are listed below:
 It allows us to take out the entire page reload and gives us the flexibility to load only a
part of the page.
 Simple API.
 Cross-Browser support.
 GET and POST supported.
 Upload JSON, XML, HTML or script document.
Q #17) Differentiate between onload() and document.ready() jQuery methods.
Answer: The difference between onload() and document.ready() methods is that the
onload() method of JavaScript will get called only after all the objects in the web
document are completely displayed/loaded.
Whereas, document.ready() method gets called when the DOM structure gets loaded in
the documents. document.ready() method gets called very fast when compared to
onload() method, as the later waits until the images are completely displayed.
Q #18) Explain the functionality of connect() method of jQuery.
Answer: jQuery connect() is a plugin that is used to connect/bind a function to another
function by assigning a handler. We can use an event of a DOM element using this
function.
Q #19) Briefly explain the bootstrap and JavaScript plug-in.
Answer: Bootstrap is a framework or toolset that includes HTML, CSS, and JavaScript to
build a webpage or web application. Many of Bootstrap components require Javascript
plugins to function.
Q #20) Explain the Applications for jQuery Mobile.
Answer: jQuery Mobile is an open-source cross-browser compatible framework designed
to build mobile applications accessible on all smartphones, tablet and desktop devices.
jQuery Mobile is created on jQuery and User Interface of jQuery for rendering various
special effects, handling Ajax request/responses, touch events, along with a variety of
widgets.
Q #21) Differentiate between jquery.min.js and jquery.js
Answer: jquery.min.js and jquery.js have the same functionality, jquery.min.js has all
empty spaces removed in order to make the file smaller in size and faster to load
resulting in script execution.
Having JS files minified in a production environment means that they will load faster and
give quick and better page performance.
Q #22) Explain the possibility of jQuery HTML method for HTML and XML
document.
Answer: jQuery HTML method is not available on XML documents, it only works for
HTML documents.
Q #23) Explain the functionality of jQuery UI (user interface).
Answer: jQuery UI is a jQuery library, that provides building various user interface
objects such as multiple record lists where the users can select, sort, drag, drop as well
as resize particular DOM elements.
UI library also creates built-in widgets such as auto-complete, checkbox, radio buttons,
datepicker, menu, etc. as well as adding an effect hide, show or toggle, and other
animations.
Q #24) Explain the functionality of a Data Table plug-in for jQuery.
Answer: Data Table is a jQuery plug-in that when applied to records is displayed in a
tabular form.
We can sort the data across single as well as multiple columns, search the specific
record, add pagination, records per page, and navigate the records in a table. Data Table
can be applied to static data, Array, data in JSON as well as AJAX response.
Q #25) Explain any of the advantages of hosting a jQuery from CDN.
Answer: Hosting jQuery from the Content Delivery Network (CDN) helps in high
availability and high performance at a lower cost and low network load, improved latency
(lesser time is taken to send and receive a data packet from server), offer a device-
specific version of contents.
Example: Responsiveness for mobile screen size, and secured storage capacity for
sensitive data or files.
Q #26) Identify any difference between .detach() and .remove() of jQuery.
Answer: detach() method of jQuery removes the selected element, however it retains
data and events. .remove() method of jQuery removes elements, data as well as events.
Q #27) Can I use a jQuery library for server scripting?
Answer: jQuery is a client-side scripting Javascript library. It can not be used for server-
side scripting.
Q #28) Can you give some situations or scenarios for using jQuery?
Answer:
We can use jQuery in the following situations/scenarios:
 We can apply a jQuery function that can change CSS static or dynamic property.
 We can call functions on events such as Form events, Keyboard events, Mouse events,
Browser events with the help of jQuery.
 We can manipulate (add, edit or delete) DOM elements using jQuery.
 jQuery can be used for animation effects on the HTML element by gradually changing
its static position to another position.
Q #29) List the four parameters used for the jQuery Ajax method.
Answer: URL address where the request is sent, Type of request viz GET or POST,
Data/content to be sent to the server and condition for the browser to either allow or not
cache the page requested are the four parameters used for jQuery Ajax method.
Q #30) Explain the functionality of the jQuery filter.
Answer: .filter() in jQuery will check for the matched element and the attribute can be
added to the matched element.
For example, for the .filter(), it can be as given below.

Line of code in jQuery.filter() API to locate/filter out list elements are as below.
$( "li" ).filter( ":even" ).css( "background-color", "yellow" );
The result of the above method call is a yellow background for texts Physics,
Mathematics, History, French, etc. that is at index 0, 2, 4 and so on, (remember index
starts from 0, hence 0 is an even) as shown in the image below.

Q #31) What special character is used as a shortcut for jQuery?


Answer: $ is used in the place of jQuery,
Example: jQuery(document).ready(function() ; can be used as $
(document).ready(function()
Q #32) Explain the different ways in which we can debug jQuery.
Answer: There are few ways in which we can debug jQuery code.
Modern-day browsers such as Google Chrome, Mozilla Firefox, Opera and Safari have
built-in Javascript debugger. To debug the jQuery code, Press F12 from your keyboard
and the browser with the built-in debugger will open a UI, wherein select the ‘Console’
menu. The error will be displayed in the console menu if any.
You can write console.log() into the code to get the error text, you can also write
debugger; in between the code line, due to debugger the script will start in debug mode,
pressing F12 into the browser will open console which will debug the code, pressing F10
will read values of the jQuery objects, and this is how we can debug jQuery code.
Q #33) Explain the possible ways in which we can include jQuery on a page.
Answer: You can download compressed production version jquery-3.4.1.min.js from
https://jquery.com/download/ site, and save it into the lib folder under the project folder.
i) We can reference jquery from the local folder at project/lib/Scripts as below.
<script src="Scripts/jquery-3.4.1.min.js"></script>
ii) We can reference from content delivery network sites such as Microsoft CDN as
below.
<script
src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.js"></script>
Q #34) Explain the functionality of .each() method in jQuery.
Answer: jQuery .each() is used to iterate / list the DOM element present in the jQuery
object.
Example
var veg_list = {
Onion,
Capsicum,
Sweet Potato,
Cauliflower,
Bitter Gourd,
Brinjal
};

$.each(veg_list, function (index, value) {


console.log(value);
});

// displays output as Onion Capsicum Sweet Potato, Cauliflower Bitter Gourd


Brinjal
Q #35) Differentiate between .prop() and .attr() methods of jQuery.
Answer: Following is the difference between .prop() and .attr().
Example:
jQuery code contains the attr() method that modifies attribute values of an image as
shown below.

.attr() method of jQuery changes attributes like width and border of the image.
$(selector).attr(attribute of the element, value to which attributes are changed to).
.prop() method in jQuery is used to return and modify DOM properties such as checked,
selected, or disabled state.
<input type="checkbox" value="pink" checked>Pink<br>
For input type as a checkbox, the value is pink and DOM property is checked,
jQuery code contains prop() method that modifies the display property of an element.

.attr() method helps us to select a value which is “pink” here, whereas .prop() method
selects property which is “checked” here.
Q #36) Explain the functionality of jQuery.noConflict.
Answer: noConflict() method of jQuery is applied to resolve conflicts when we need to
use frameworks, other than jQuery.
For example, many JavaScript libraries such as Mootools, prototype, zepto, etc. use $, a
function or variable name, that is used as a replacement of text jQuery in the jQuery
code, and in such cases, .noConflict() method allows to use $ shortcut identifier, by
allowing other scripts to use it.
Q #37) Differentiate between width() vs css(‘width’) in jQuery.
Answer: There are two different methods in jQuery to change the width of an element.
The first way is to use .css(property) and the other way is to use .property().
Example:
$(selector).css(property,value_change);
$(selector).property(value_change);
In .css(property) which in this case is width, we have to add px in the value_change, say
300px.
We can use .property(value_change), which in this case is width, and you need not have
to add px, but direct value.
Q #38) Where can we apply the param() method in jQuery?
Answer: We can display array, plain object or jquery object in the form of a stream of
bytes so that they can be stored into memory, file or database using param() method in
jQuery.
Q #39) Differentiate between $(this) and this in jQuery.
Answer: $(this) is a jQuery object, whereas this is a JavaScript’s global object reference,
using this we can refer DOM element in HTML document.
$(this) references to the parent object, whereas this refers to a DOM element, which in
the case of an array, represents an object with .each() method, that displays the current
iteration.
Q #40) Describe the functionality of read cookies, write cookies and delete
cookies in jQuery.
Answer: When websites are visited, cookies are data values such as the name of the user
that gets stored in small text files on the computer. While revisiting websites, the cookies
help to remember the user’s name. JavaScript and jQuery create, read and delete
cookies, with the document.cookie property.
Q #41) What is the use of the serialize() method in jQuery?
Answer: It serializes the form values so that its serialized values can be used in the URL
query string while making an AJAX request.
.serialize() method of jQuery returns the input values of HTML form in the form of string.
Q #42) What is the use of the val() method in jQuery?
Answer: .val() method helps to find the value of an attribute of HTML element. For
example, form elements such as input, select and textarea. Val() is also applied to find
the value of all matched elements from checkboxes and radio buttons as well as a drop-
down list.
Example explained with syntax
// form elements such as dropdown with select tag and id mylst, the value of the selected
option will have syntax as below
$( "select#mylst option:checked" ).val();
// form element such as a set of radio buttons with input type as radio and name rdobtn,
the value can be retrieved
$( "input[type=radio][name=rdobtn]:checked" ).val();
Q #43) What is Method Chaining in jQuery? What advantages does it offer?
Answer: With jQuery method chaining, multiple actions can be applied on a single line of
code, as all the methods return jQuery objects that can be utilized to call another method.
Without chaining, jQuery methods are called one after another in a separate line,
whereas with chaining, jQuery methods are written in dot separated single line of code.
Without chaining multiple lines of code that need to be written, making jQuery to search
entire DOM for matched element, then single methods in each line of code are applied.
Whereas Chaining needs only a one-time selection of a matched element from DOM, by
making better performance.
Q #44) What is the difference between jQuery.get() and jQuery.ajax() ?
Answer: jQuery.ajax() method is used to send HTTP Ajax requests, whereas jQuery.get()
method is used to send HTTP GET requests to load data from the server.
Q #45) What is QUnit?
Answer: QUnit is a framework, which tests JavaScript code written for jQuery, jQuery UI,
and jQuery Mobile, uses assertions and test fixtures for verifying the expected results.
Q #46) How jQuery stores data related to an element?
Answer: jQuery.data() method aids in attaching any type of data to DOM elements, free
from memory leaks. jQuery makes sure that data is removed along with the DOM
elements removed via jQuery methods.
Code for Storing and retrieving data related to an element.
$('#myDiv').data('keyName', { foo : 'bar'});
$('#myDiv').data('keyName'); // { foo : 'bar'}
Q #47) Can you explain the various procedures of extracting a query string with
regular expressions?
Answer: We can accomplish extracting a query string with regular expression in the
following two ways.
1. String-based approach: This method helps in deriving String by comparing
equivalent regular expression, using .replace() method.
2. Regular expression approach: A most powerful method for extracting a query
string and pattern must be used that is compared with strings in JavaScript.
Using .exec() and .test() methods for comparing with patterns. match(), matchAll(),
replace(), search() and split() are other few methods for String.
Q #48) Explain the concept of the finish method in jQuery.
Answer: In order to stop all the queued animations and to help them place in their final
state the .finish() method is used.
Q #49) Differentiate between calling stop (true, true) and finish method.
Answer: .finish() method helps in clearing the queue & helps the animations to enter into
their end state, whereas .stop() method is called on an element, by forcing currently
running animation to stop instantly.
Q #50) How can you write a browser-specific code using jQuery?
Answer: We can write browser-specific code in jQuery using navigator.userAgent to
identify, the browser from Internet Explorer, Chrome, Firefox, Safari, and Opera, as the
code written below.
if (navigator.userAgent.search("MSIE") >= 0) {
// JQuery Code once navigator.userAgent identifies Microsoft Internet
Explorer browser.
}
else if (navigator.userAgent.search("Chrome") >= 0) {
// JQuery Code once navigator.userAgent identifies Google Chrome browser.
}

else if (navigator.userAgent.search("Firefox") >= 0) {


// JQuery Code once navigator.userAgent identifies Mozilla Firefox browser.
}

else if (navigator.userAgent.search("Safari") >= 0 &&


navigator.userAgent.search("Chrome") < 0) {
// JQuery Code once navigator.userAgent identifies either Safari or Chrome
browser type.
}

else if (navigator.userAgent.search("Opera") >= 0) {


// JQuery Code once navigator.userAgent identifies Opera browser.
}
Q #51) What is the procedure to check the data type of any variable in jQuery?
Answer: jQuery function type() is used in order to identify the data type of any variable
such as an array, string, number, function or object data type.
jQuery Tips
Use noConflict()
The $ alias used by jQuery is also used by other JavaScript libraries. To ensure that
jQuery doesn't conflict with the $ object of different libraries, use the noConflict() method
at the start of the document:
jQuery.noConflict();
Now you'll reference the jQuery object using the jQuery variable name instead
of $ (e.g., jQuery('div p').hide()). If you have multiple versions of jQuery on the same page
(not recommended), you can use noConflict() to set an alias to a specific version:
let $x = jQuery.noConflict();
Checking If jQuery Loaded
Before you can do anything with jQuery you first need to make certain it has loaded:
if (typeof jQuery == 'undefined') {
console.log('jQuery hasn\'t loaded');
} else {
console.log('jQuery has loaded');
}
Now you're off...
Check Whether an Element Exists
Prior using a HTML element you need to ensure it's part of DOM.
if ($("#selector").length) {
//do something with element
}
Use .on() Binding Instead of .click()
Using .on() gives you several advantages over using .click(), such as the ability to add
multiple events...
.on('click tap hover')
...a binding applies to dynamically created elements, as well (there's no need to manually
bind every single element dynamically added to a DOM element)...
...and the possibility to set a namespace:
.on('click.menuOpening')
Namespaces give you the power to unbind a specific event
(e.g., .off('click.menuOpening')).
Back to Top Button
By using the animate and scrollTop methods in jQuery you don't need a plugin to create a
simple scroll-to-top animation:
// Back to top
$('.container').on('click', '.back-to-top', function (e) {
e.preventDefault();
$('html, body').animate({scrollTop: 0}, 800);
});
<!-- Create an anchor tag -->
<div class="container">
<a href="#" class="back-to-top">Back to top</a>
</div>
Changing the scrollTop value changes where you wants the scrollbar to land. All you're
really doing is animating the body of the document throughout the course of 800
milliseconds until it scrolls to the top of the document.
Example:
<style>
#scrollToTopBtn {
display: none;
position: fixed;
bottom: 20px;
right: 20px;
font-size: 15px;
font-weight: 600;
border: none;
outline: none;
background-color: #555;
color: white;
cursor: pointer;
border-radius: 50%;
width: 52px;
height: 52px;
display: inline-flex;
align-items: center;
justify-content: center;
}
</style>
<div class="content">
<!-- Your website content here -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do
eiusmod tempor incididunt ut labore et dolore
magna aliqua.</p>
<!-- A long content to enable scrolling -->
</div>

<button id="scrollToTopBtn" title="Go to top">Top</button>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
// show or hide the scroll to top button based on scroll position

$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$("#scrollToTopBtn").fadeIn();
} else {
$("#scrollToTopBtn").fadeOut();
}
});

// smooth scrolling to top


$("#scrollToTopBtn").click(function () {
$("html, body").animate({
scrollTop: 0
}, 800);
return false;
})
});
</script>
Preload Images
If your web page uses a lot of images that aren't visible initially (e.g., on hover) it makes
sense to preload them:
$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};

$.preloadImages('img/hover-on.png', 'img/hover-off.png');
Checking If Images Are Loaded
Sometimes you might need to check if your images have fully loaded in order to continue
on with your scripts:
$('img').on('load', function () {
console.log('image load successful');
});
You can also check if one particular image has loaded by replacing the <img> tag with
an ID or class.
Fix Broken Images Automatically
If you happen to find broken image links on your site replacing them one by one can be a
pain. This simple piece of code can save a lot of headaches:
$('img').on('error', function () {
if(!$(this).hasClass('broken-image')) {
$(this).prop('src', 'img/broken.png').addClass('broken-image');
}
});
Alternatively, if you wish to hide broken images this snippet will take care of that for:
$('img').on('error', function () {
$(this).hide();
});
Post a Form with AJAX
jQuery AJAX methods are a common way to request text, HTML, XML, or JSON. If you
wanted to send a form via AJAX you could collect the user inputs via the val() method:
$.post('sign_up.php', {
user_name: $('input[name=user_name]').val(),
email: $('input[name=email]').val(),
password: $('input[name=password]').val(),
});
But all of those val() calls are expensive and using .val() on <textarea> elements will
strip carriage return characters from the browser-reported value. A better way of
collecting user inputs is using the serialize() function which collects them as a string:
$.post('sign_up', $('#sign-up-form').serialize());
Toggle Classes on Hover
Let's say you want to change the visual of a clickable element on your page when a user
hovers over it. You can add a class to your element when the user is hovering; when the
user stops hovering removes the class:
$('.btn').on('hover', function () {
$(this).addClass('hover');
}, function () {
$(this).removeClass('hover');
});
You need to add the necessary CSS. If you want an even simpler way use
the toggleClass method:
$('.btn').on('hover', function () {
$(this).toggleClass('hover');
});
Note: CSS may be a faster solution in this case but it's still worthwhile to know this.
Disabling Input Fields
At times you may want the submit button of a form or one of its text inputs to be disabled
until the user has performed a certain action (e.g., checking the "I've read the terms"
checkbox). Add the disabled attribute to your input so you can enable it when you want:
$('input[type="submit"]').prop('disabled', true);
All you need to do is run the prop method again on the input, but set the value
of disabled to false:
$('input[type="submit"]').prop('disabled', false);
Stop the Loading of Links
Sometimes you don't want links to go to a certain web page nor reload the page; you
might want them to do something else like trigger another script. This will do the trick of
preventing the default action:
$('a.no-link').on('click', function (e) {
e.preventDefault();
});
Cache jQuery Selectors
Think of how many times you write the same selector over and over again in any project.
Every $('.element') selector has to search the entire DOM each time, regardless if that
selector had previously run. Instead you can run the selector once and store the results in
a variable:
var blocks = $('#blocks').find('li');
Now you can use the blocks variable wherever you want without having to search the
DOM every time:
$('#hideBlocks').on('click', function () {
blocks.fadeOut();
});

$('#showBlocks').on('click', function () {
blocks.fadeIn();
});
Caching jQuery selectors is a good performance gain.
Toggle Fade/Slide
Sliding and fading are common in animations with jQuery. You might want to show an
element when a user clicks something, which makes the fadeIn and slideDown methods
perfect, but if you want that element to appear on the first click and then disappear on
the second, this will work fine:
// Fade
$('.btn').on('click', function () {
$('.element').fadeToggle('slow');
});

// Toggle
$('.btn').on('click', function () {
$('.element').slideToggle('slow');
});
Simple Accordion
This is a simple method for a quick accordion:
// Close all panels
$('#accordion').find('.content').hide();

// Accordion
$('#accordion').find('.accordion-header').on('click', function () {
var next = $(this).next();
next.slideToggle('fast');
$('.content').not(next).slideUp('fast');
return false;
});
By adding this script all you really need to do on your web page is the necessary HTML to
get this working.
Example:
<style>
.accordion {
margin-bottom: 10px;
overflow: hidden;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
}

.accordion-item {
margin-bottom: 12px;
}

.accordion-header {
background-color: rgb(34, 11, 99);
padding: 10px;
cursor: pointer;
font-weight: 600;
border-radius: 4px;
color: #fff;
text-transform: uppercase;
}

.accordion-content {
padding: 10px;
display: none;
background-color: #fff;
margin-top: 8px;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 4px;
}

.accordion-item.active .accordion-content {
background-color: #f5f5f5;
}
</style>
<div class="accordion" id="accordion">
<div class="accordion-item">
<div class="accordion-header">Section 1</div>
<div class="accordion-content">Lorem ipsum dolor sit amet, consectetur
adipiscing elit.</div>
</div>

<div class="accordion-item">
<div class="accordion-header">Section 2</div>
<div class="accordion-content">Sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.</div>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$('#accordion').find('.accordion-content').hide(); // Close all panels

$('#accordion').find('.accordion-header').on('click', function () {
var accordionItem = $(this).parent('.accordion-item');
var next = $(this).next('.accordion-content');

accordionItem.toggleClass("active").siblings().removeClass("active"); //
Toggle active class for accordion item

next.slideToggle('fast'); // Slide toggle the content


$('.accordion-content').not(next).slideUp('fast');
return false;
});
});
</script>

Tabs
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

html,
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
padding: 0 16px;
}
.tabs_wrapper {
max-width: 800px;
margin: 16px auto;
padding: 8px;
}

.tabs_head_container {
display: flex;
align-items: center;
flex-wrap: wrap;
list-style-type: none;
gap: 6px;
}

.tabs_head_container li {
cursor: pointer;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}

.tabs_head_btn {
color: rgb(29, 19, 119);
text-align: center;
text-decoration: none;
border-radius: 4px;
padding: 2px 12px;
min-width: 100px;
border: 2px solid rgb(29, 19, 119);
transition: all 300ms ease-in-out;
}

.tabs_head_btn.active {
background: rgb(29, 19, 119);
color: #fff;
}

.tab_content_container {
background: #fff;
border-radius: 0 0 10px 10px;
margin-top: 10px;
}

.tab_content {
display: none;
padding: 16px;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 4px;
}

.tab_content h3 {
margin-bottom: 8px;
}

.tab_content_active {
display: block;
}

.tab_content_active span {
float: left;
width: 100px;
margin-right: 20px;
}
</style>
<div class="tabs_wrapper">
<ul class="tabs_head_container">
<li><a href="javascript:void(0); return false;" rel="#tabcontent1"
class="tab tabs_head_btn active">TAB 1</a></li>
<li><a href="javascript:void(0); return false;" rel="#tabcontent2"
class="tab tabs_head_btn">TAB 2</a></li>
<li><a href="javascript:void(0); return false;" rel="#tabcontent3"
class="tab tabs_head_btn">TAB 3</a></li>
</ul>

<div class="tab_content_container">
<div class="tab_content tab_content_active" id="tabcontent1">
<h3>What Is Loren Ipsum ?</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the
industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and
scrambled it to make a type specimen book. It has survived not
only five centuries, but also the leap into
electronic typesetting, remaining essentially unchanged. It was
popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus
PageMaker including versions of Lorem Ipsum.</p>
</div>

<div class="tab_content" id="tabcontent2">


<h3>Why do we use ?</h3>
<p>It is a long established fact that a reader will be distracted by
the readable content of a page when looking
at its layout. </p>
</div>

<div class="tab_content" id="tabcontent3">


<h3>Where does it come from ?</h3>
<p>Contrary to popular belief, Lorem Ipsum is not simply random
text. It has roots in a piece of classical Latin
literature from 45 BC, making it over 2000 years old. </p>
</p>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$(".tabs_wrapper").on("click", ".tabs_head_btn", function (e) {
e.preventDefault();
$(".tabs_head_container .tabs_head_btn").removeClass("active");
$(this).addClass('active');

const target = $(this).attr('rel');


$(".tab_content_container
> .tab_content_active").removeClass("tab_content_active").hide();
$(target).fadeIn(500).addClass("tab_content_active");
});
});
</script>

Make Two Divs the Same Height


Sometimes you'll want two divs to have the same height no matter what content they
have in them:
$('.div').css('min-height', $('.main-div').height());
This example sets the min-height which means that it can be bigger than the main div but
never smaller. However, a more flexible method would be to loop over a set of elements
and set height to the height of the tallest element:
var $columns = $('.column');
var height = 0;
$columns.each(function () {
if ($(this).height() > height) {
height = $(this).height();
}
});
$columns.height(height);
If you want all columns to have the same height:
var $rows = $('.same-height-columns');
$rows.each(function () {
$(this).find('.column').height($(this).height());
});
Note: This can be done several ways in CSS but depending on what your needs are,
knowing how to do this in jQuery is handy.
Open External Links in New Tab/Window
Open external links in a new browser tab or window and ensure links on the same origin
open in the same tab or window:
$('a[href^="http"]').attr('target', '_blank');
$('a[href^="//"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');
Find Element By Text
By using the contains() selector in jQuery you can find text in content of an element. If
text doesn't exists, that element will be hidden:
var search = $('#search').val();
$('div:not(:contains("' + search + '"))').hide();
Trigger on Visibility Change
Trigger JavaScript when the user is no longer focusing on a tab or refocuses on a tab:
$(document).on('visibilitychange', function (e) {
if (e.target.visibilityState === 'visible') {
console.log('Tab is now in view!');
} else if (e.target.visibilityState === 'hidden') {
console.log('Tab is now hidden!');
}
});
AJAX Call Error Handling
When an AJAX call returns a 404 or 500 error, the error handler will be executed. If the
handler isn't defined, other jQuery code might not work as intended. To define a global
AJAX error handler:
$(document).on('ajaxError', function (e, xhr, settings, error) {
console.log(error);
});
Chain Plugin Calls
jQuery allows for the "chaining" of plugin method calls to mitigate the process of
repeatedly querying the DOM and creating multiple jQuery objects. Let's say the
following snippet represents your plugin method calls:
$('#elem').show();
$('#elem').html('bla');
$('#elem').otherStuff();
This could be vastly improved by using chaining:
$('#elem')
.show()
.html('bla')
.otherStuff();
An alternative is to cache the element in a variable (prefixed with $):
var $elem = $('#elem');
$elem.hide();
$elem.html('bla');
$elem.otherStuff();
Both chaining and caching methods in jQuery are best practices that lead to shorter and
faster code.
Sort List Items Alphabetically
Let's say you end up with too many items in a list. Maybe the content is produced by a
CMS and you want to order them alphabetically:
var ul = $('#list'),
lis = $('li', ul).get();

lis.sort(function (a, b) {
return ($(a).text().toUpperCase() < $(b).text().toUpperCase()) ? -1 : 1;
});

ul.append(lis);
There you go!
Disable Right-Click
If you want to disable right-click, you can do it for an entire page...
$(document).ready(function () {
$(document).bind('contextmenu', function (e) {
return false;
})
})
...and you can also do the same for a specific element:
$(document).ready(function () {
$('#submit').bind('contextmenu', function (e) {
return false;
})
})

Equal-Height Columns
Columns with equal heights have always been a problem for designers using divs,
although now, there are quite a few solutions. Among the solutions available to you is
using jQuery. This technique only requires a very small JavaScript function to handle
everything, then some basic integration with the main layout to make the magic happen.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<style>
.container {
display: flex;
align-items: center;
}

div[class^="col"] {
background: rgba(0, 0, 0, 0.2);
width: 33.3333%;
padding: 0.6rem;
}
</style>
</head>

<body>

<div class="container">
<div class="col1">Lorem ipsum dolor sit amet consectetur adipisicing
elit. Tempora eius cumque qui hic blanditiis
saepe accusantium quo ab minus beatae?</div>
<div class="col2">Lorem, ipsum dolor sit amet consectetur adipisicing
elit. Voluptatem modi nostrum quas rem
similique
consequuntur perspiciatis et non ea molestiae, numquam est pariatur
omnis doloremque quaerat. Debitis atque, ea
nobis odit nam eligendi error laudantium ullam. Amet officia sed
nihil.</div>
<div class="col3">Lorem ipsum dolor, sit amet consectetur adipisicing
elit. Iusto quibusdam provident enim inventore
qui quas veniam aliquid nisi, expedita laborum, aliquam fugiat nemo ad
temporibus ea delectus? A, quas deserunt.
Culpa sed similique, asperiores perferendis molestiae eius odit
corrupti, dolore vero atque, ut consectetur?
Deserunt, maxime quidem! Corporis rerum soluta veniam! Dolor, quo
cupiditate perspiciatis dignissimos blanditiis
dolore! Earum, harum.</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function () {
function equalHeight(group) {
var tallest = 0;
group.each(function () {
var thisHeight = $(this).height();
if (thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}

equalHeight($(".container > div"));

$(window).on('resize', function () {
$(".container > div").height('auto');
equalHeight($(".container > div"));
});
})
</script>
</body>
</html>
Disabling Right Mouse Click
If you are to disable right click on your web browser, you can use the following piece of
code:
$(document).ready(function(){
$(document).bind(“contextmenu”,function(e){
return false;
});
});
Determine Browser
Suppose you were to determine the browser type of the browser currently in use. You can
use the following piece of code to do this:
$(document).ready(function() {
// If the browser type if Mozilla Firefox
if ($.browser.mozilla && $.browser.version >= "1.8" ){
// some code
}
// If the browser type is Opera
if( $.browser.opera)
{
// some code
}
// If the web browser type is Safari
if( $.browser.safari )
{
// some code
}
// If the web browser type is Chrome
if( $.browser.chrome)
{
// some code
}
// If the web browser type is Internet Explorer
if ($.browser.msie && $.browser.version <= 6 )
{
// some code
}
//If the web browser type is Internet Explorer 6 and above
if ($.browser.msie && $.browser.version > 6)
{
// some code
}
});
Check if an Element Is Visible
To check whether an element is visible, you can use the following piece of code:
if($(element).is(":visible") == "true")
{
//The DOM element is visible
}
else
{
//The DOM element is invisible
}
Smooth(animated) page scroll
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smooth Scroll Example</title>
<style>
/* Add your CSS styles here */
</style>
</head>
<body>
<a href="#top" class="scroll-link">Go to Top</a>
<div style="height: 2000px;">
<!-- A tall div to demonstrate scrolling -->
</div>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function() {
$('.scroll-link').click(function(event) {
event.preventDefault();

var target = $(this).attr('href');

if ($(target).length) {
var targetOffset = $(target).offset().top;
$('html, body').animate({
scrollTop: targetOffset
}, 900);
}
});

// Debounce function to improve performance on window resize


function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}

// Smooth scrolling on window resize


var smoothScrollOnResize = debounce(function() {
var target = $('.scroll-link').attr('href');

if ($(target).length) {
var targetOffset = $(target).offset().top;
$('html, body').animate({
scrollTop: targetOffset
}, 900);
}
}, 250);

$(window).on('resize', smoothScrollOnResize);
});
</script>
</body>
</html>
CSS Style Switcher
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Theme Switcher Example</title>
<!-- Default stylesheet -->
<link rel="stylesheet" href="default.css">
<style>
/* Add your CSS styles here */
</style>
</head>
<body>

<header>
<!-- Theme switch links -->
<a href="#" class="styleswitcher" rel="default.css">Default Theme</a>
<a href="#" class="styleswitcher" rel="red.css">Red Theme</a>
<a href="#" class="styleswitcher" rel="blue.css">Blue Theme</a>
</header>

<!-- Your content goes here -->


<h1>Welcome to the Theme Switcher Example</h1>
<p>This is your content.</p>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></
script>
<script>
$(document).ready(function() {
// Function to switch themes
$("a.styleswitcher").click(function(event) {
event.preventDefault();
var newTheme = $(this).attr('rel');

// Switch the stylesheet


$('link[rel="stylesheet"]').attr('href', newTheme);
});
});
</script>
</body>
</html>
jQuery's Shorthand Ready Method
Listening for when the document is ready to be manipulated is laughably simple with
jQuery.
$(document).ready(function() {
// let's get up in heeya
});
Though, it's very possible that you might have come across a different, more confusing
wrapping function.
$(function() {
// let's get up in heeya
});
Though the latter is somewhat less readable, the two snippets above are identical. Don't
believe me? Just check the jQuery source.
// HANDLE: $(function)
// Shortcut for document ready
if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
rootjQuery is simply a reference to the root jQuery(document). When you pass a selector
to the jQuery function, it'll determine what type of selector you passed: string, tag, id,
function, etc. If a function was passed, jQuery will then call its ready() method, and pass
your anonymous function as the selector.
Keep your Code Safe
If developing code for distribution, it's always important to compensate for any possible
name clashing. What would happen if some script, imported after yours, also had
a $ function? Bad stuff!
The answer is to either call jQuery's noConflict(), or to store your code within a self-
invoking anonymous function, and then pass jQuery to it.
Method 1: NoConflict
var j = jQuery.noConflict();
// Now, instead of $, we use j.
j('#someDiv').hide();
// The line below will reference some other library's $ function.
$('someDiv').style.display = 'none';
Be careful with this method, and try not to use it when distributing your code. It would
really confuse the user of your script! :)
Method 2: Passing jQuery
(function($) {
// Within this function, $ will always refer to jQuery
})(jQuery);
The final parens at the bottom call the function automatically - function(){}(). However,
when we call the function, we also pass jQuery, which is then represented by $.
Method 3: Passing $ via the Ready Method
jQuery(document).ready(function($) {
// $ refers to jQuery
});
// $ is either undefined, or refers to some other library's function.
Sticky Navbar
<style>
body {
margin: 0;
padding: 0;
}

.header {
padding: 24px 0;
background-color: #000;
}

.nav {
padding: 24px 0;
background-color: rgb(179, 0, 0);
position: -webkit-sticky;
}

.header,
.nav {
text-align: center;
color: #fff;
}

.content {
width: 600px;
margin: 10px auto 100px;
}

.sticky {
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 100;
border-top: 0;
}
</style>

<div class="wrapper">
<div class="header">
HEADER CONTENT
</div>
<div class="nav">
WHATEVER YOU WANT TO BE STICKY
</div>
<div class="content">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make
a type specimen book. It has survived not only five centuries, but
also the leap into electronic typesetting,
remaining essentially unchanged. It was popularised in the 1960s
with the release of Letraset sheets containing
Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions
of Lorem Ipsum.</p>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
// grab the initial top offset of the navigation
let stickyNavTop = $(".nav").offset().top;

let stickyNav = function () {


let scrollTop = $(window).scrollTop();
// if we've scrolled more than the navigation, change its position
to fixed to stick to top, otherwise change it back to relative
if (scrollTop > stickyNavTop) {
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
// shortcut: $('.nav').toggleClass('sticky', scrollTop >
stickyNavTop);
};

stickyNav();
// and run it again every time you scroll
$(window).scroll(function () {
stickyNav();
});

});
</script>

Custom Scrollspy
<style>
* {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}

body {
margin: 0px;
padding: 0px;
}

#nav-container {
position: fixed;
width: 100%;
padding: 1em 0;
background-color: #fff;
}

#nav {
display: flex;
justify-content: space-evenly;
height: 3em;
line-height: 3em;
}

a:link,
a:visited,
a:active {
text-decoration: none;
font-family: 'Raleway', sans-serif;
font-weight: 700;
color: #000;
}

a:hover {
color: #85D6CB;
}

.nav-link {
padding: 0 1em;
margin: 0 3em;
border-radius: 2em;
transition: all .4s;
}

a.active {
color: #fff;
}

a.nav-link.active:hover {
padding: 0 4em;
margin: 0;
}

section {
height: 100vh;
}

#home,
a.active[href="#home"] {
background-color: #85D6CB;
}

#about,
a.active[href="#about"] {
background-color: #339CC7;
}

#work,
a.active[href="#work"] {
background-color: #0378A6;
}

#contact,
a.active[href="#contact"] {
background-color: #005778;
}
</style>

<div id="nav-container">
<div id="nav">
<a href="#home" class="nav-link active">Home</a>
<a href="#about" class="nav-link">About</a>
<a href="#work" class="nav-link">Work</a>
<a href="#contact" class="nav-link">Contact</a>
</div>
</div>

<section id="home">
</section>
<section id="about">
</section>
<section id="work">
</section>
<section id="contact">
</section>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function () {
let link = $("#nav a");

// move to specific section when click on menu link


link.on('click', function (e) {
let target = $($(this).attr('href'));
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
$(this).addClass('active');
e.preventDefault();
});

function scrNav() {
let sTop = $(window).scrollTop();
$('section').each(function () {
let id = $(this).attr('id');
let offset = $(this).offset().top - 1;
let height = $(this).height();

if (sTop >= offset && sTop < offset + height) {


link.removeClass('active');
$('#nav').find(`a[href="#${id}"]`).addClass('active');
}
})
}

scrNav();

$(window).on('scroll', function () {
scrNav();
});
});
</script>
Scroll Progress Bar
<style>
.header {
position: fixed;
top: 0;
width: 100%;
z-index: 1;
}

.progress-container {
background-color: rgba(150, 150, 150, 0.6);
height: 10px;
width: 100%;
}

.progress-bar {
background-color: #2196f3;
height: 10px;
width: 0%;
}

.content {
padding: 2em;
}

/* general styling */
body {
font-family: -apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
Oxygen-Sans,
Ubuntu,
Cantarell,
"Helvetica Neue",
sans-serif;
line-height: 1.75;
margin: 0;
}
</style>
<div class="header">
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
</div>

<div class="content">
<h1>Scroll Progress Bar</h1>
<p>Cake icing danish caramels chocolate muffin. Muffin halvah halvah
chocolate cake wafer ice cream lemon drops
croissant cake. Liquorice cheesecake tiramisu sweet roll fruitcake
biscuit cheesecake jujubes icing. Danish
jelly-o donut lollipop. </p>

</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
const progressBar = $("#progressBar");

function updateProgressBar() {
const winScroll = $(window).scrollTop();
const height = $(document).height() - $(window).height();
const scrolled = (winScroll / height) * 100;
progressBar.width(scrolled + "%");
}

$(window).on('scroll resize', updateProgressBar);


updateProgressBar();
});
</script>

You might also like