JQuery Interview
JQuery Interview
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.
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: 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>
});
</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>
});
</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>
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>
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.
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>
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>
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>
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>
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>
<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>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>
<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>
<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>
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.
<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.
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.
<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:
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
}];
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.
.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.
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.
<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.
<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.
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.
<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.
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.
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`);
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.
<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.
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 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.
$("#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.
$("#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.
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.
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();
});
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.
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);
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.
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:
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.
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);
});
// 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);
});
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);
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);
});
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);
});
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.");
});
});
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.
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.
.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.
}
<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();
}
});
$.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
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>
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);
}
$(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();
if ($(target).length) {
var targetOffset = $(target).offset().top;
$('html, body').animate({
scrollTop: targetOffset
}, 900);
}
});
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>
<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');
.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;
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");
function scrNav() {
let sTop = $(window).scrollTop();
$('section').each(function () {
let id = $(this).attr('id');
let offset = $(this).offset().top - 1;
let height = $(this).height();
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 + "%");
}