10 JQuery Class Note
10 JQuery Class Note
10 JQuery Class Note
jQuery
10.1 What is jQuery? Why do we need it and what can we do with it?
• Definition:
• jQuery is just a JavaScript library that you include on your web page. As jQuery is
built on top of JavaScript, it provides all the functionalities of JavaScript. We can say
from above points jQuery is enhanced version of JavaScript.
• As a library, it provides many built-in functions using which you can accomplish
various tasks easily and quickly.
• jQuery is different from vanilla JavaScript because is basically a simpler way of doing
things in a more compatible way
• jQuery library contains features like HTML/DOM manipulation, CSS manipulation,
CSS manipulation and effects and animations
• What can you do with jQuery? jQuery is JavaScript and does not add anything to the
JavaScript language itself. Whatever you do with vanilla JavaScript, you can do it with jQuery
too. But jQuery does the following jobs in a very easy way for developers:
• DOM manipulation:
▪ Selecting: jQuery provides simpler and CSS-like way of selecting HTML
elements
▪ Updating: Multiple jQuery methods provide different ways to update, animate
and loop through elements in a much simpler way
• Handling events: Allows you to bind events with elements without the need to write
a fall back for older versions
• Effects and animations: jQuery also allows us to add animated effects on our web
page which takes a lot of pain and lines of code with JavaScript.
• Why is jQuery chosen?
o Simplicity: The main reason we need jQuery is because it makes JavaScript easier when
we use it on website, in fact, jQuery’s motto is "write less, do more". How?
▪ jQuery takes a lot of common tasks that require many lines of vanilla JavaScript
code to accomplish and wraps them into methods that you can call with a single
line of code.
▪ DOM manipulation in jQuery is simplified: The jQuery made it easy to select
DOM elements, negotiate them and modify them using a cross-browser open-
source selector engine called Sizzle
▪ Loop through elements
▪ Simplified animation and fading of elements
▪ Better event handling
▪ Cross browser compatibility: Unlike vanilla JavaScript , jQuery provides a
consistent result throughout major browsers
o Simpler selection and updating method: If you use vanilla JavaScript, some methods
that you use for selection do not work on older browsers
o jQuery is Easy to learn: jQuery is very simple as it is built on a shorter code than
JavaScript. Also, the developers don’t need any design talent or learn web designing as
uses of jQuery provides an abundant set of built-in plugins.
• jQuery selectors: They select HTML elements based on their name, id, classes, types,
attributes, values of attributes and much more.
▪ jQuery selectors mostly use the existing CSS Selectors and, in some instances,
custom selectors.
▪ jQuery() vs $(): All jQuery selectors use a function called jQuery(). However,
there is a shorthand representation of the jQuery() method, just using the dollar
sign at the start and add parentheses like this: $().
• Therefore, jQuery() is the same as $()
• Note 1: The jQuery function/ jQuery() always returns a jQuery object (that
is based on an array). You will see this in example when jQuery selectors
are explained
• Note 2: Please note that jQuery() returns an object even if there are no
elements that matches the selector. If the jQuery object contains no
elements, it will simply do nothing.
• jQuery #id Selector: jQuery #id selector uses the id attribute of an HTML tag to find the
specific element. Let’s use the following HTML to explain id, class and element selectors
in jQuery
▪ Example: Let’s select an element that has id name called “myParagraph”
<div class="myDiv">jQuery</div>
<div>
</div>
• jQuery element selector: jQury element selector selects elements based on the element
name.
▪ Example: Using the above HTML, let’s select our span element
• jQuery (filters): jQuery provides several filter methods to narrow down the search for
elements in a DOM tree.
▪ first(): The first() method filters the set of matched elements and returns the first
element of the specified elements. Example: The script below will select all <li>s
and filters the first <li> only and change its background color to pink
$("li").first().css("background-color", "pink");
▪ last(): This method returns the last element of the specified elements. Example:
The script below will select all <li>s and filters the last<li> only and change its
background color to pink
$("li").last().css("background-color", "pink");
▪ even() and odd() : These method filter the set of matched/selected elements and
returns those with an even/odd index number. Example: Let’s select all <li>s and
make background color of those <li>s with even index green and make background
color of those <li>s with odd index purple
$("li").even().css("background-color", "green");
$("li").odd().css("background-color", "purple");
▪ nth-child() or nth-children(): This method selects all elements that are the nth
child/children, of their parent. Note: The element type is not considered here, if it
is the nth child, this method returns that element. Example: Let’s select a <ul> that
has <li>s as children and change the background color of the 2nd child <li> only
▪ Content filters
• has(selector): This method filters the set of matched elements and returns
only those elements that has the specified descendant element. Note: To
select elements that have multiple elements inside of them, use comma.
Example: Let’s select a <div> that has <p> in it, and change this <div>’s
background color
$("div").has("p").css("background-color", "pink");
• empty(): The empty() method removes all child nodes and content from
the selected elements.
▪ Visibility
• hidden(): This method hides the selected elements just like CSS property
display: none. Example: let’s hide our <ul> that has id name of firstUL
$(" ul").show();
10.5 Updating or altering values: content and elements
• jQuery object has many methods that you can use on the element that you select. These are
the common methods that you will use. Methods to get or change content of elements,
attributes or nodes
• Updating content:
▪ html(): This method sets/returns the content of selected elements (including
HTML markup). Example: Let’s print in the console the text, including our <li>
tag, of our <li> that has a specific class name
console.log($("li[class=otherLi]").html());
▪ text(): The method sets/returns the text content of selected elements. Example:
Let’s print in the console the text of our <li> that has a specific class name
console.log($("li[class=firstLi]").text());
▪ remove() and empty(): The remove() method removes the selected element and
all its child elements. The empty() method removes only the child elements of the
selected element, meaning, the selected element itself will not be removed, but its
child/children. This method sets/returns the value of form fields. Example: Let’s
remove our <div> and its child <p>s first and then go to emptying our <div>’s
children. Notice: We styled our <div> to show that it won’t be affected by empty()
method.
<p>I am first</p>
<p>I am second</p>
<p>I am third</p>
</div>
<p>I am second</p>
<p>I am third</p>
</div>
$("#divId").before($("#firstPar"));
▪ after(): The after() method inserts specified content in behind the selected
elements. Example: Let’s put our <p> with id="firstPar" right after our <div>
<p>I am second</p>
<p>I am third</p>
</div>
$("#divId").after($("#firstPar"));
▪ prepend(): The prepend() method inserts specified content inside the selected
element at the beginning of this selected element. In short, it puts the selected
element at the first index. Example: Let’s put our <p> that has “firstPar” id at the
beginning of our <div>
<p>I am second</p>
<p>I am third</p>
</div>
$("#divId").prepend($("#firstPar"));
▪ append(): The append() method inserts specified content inside the selected
element at the end of this selected element. In short, it puts the selected element
inside an element at the last index. Example: Let’s put our <p> that has “firstPar”
id at the end of our <div>
<p>I am second</p>
<p>I am third</p>
</div>
$("#divId").append($("#firstPar"));
10.6 Altering values: attributes, form value, looping through elements
• Attributes:
▪ addClass(): This method adds one or more property (CSS class) to each selected
element. This method does not remove existing class attributes, it only adds one or
more class names to the class attribute. Example: Let’s add two CSS classes to
our paragraphs using addClass() and change their background and text color.
$("p").addClass("classOne classTwo");
$("p").removeClass("classOne");
▪ css(): The css() method in JQuery is used to change the style property of the
selected element. Example: Let’s change the background color of our <p>tags
using the css() method
$("p").css("background-color", "green");
• Form value:
▪ val(): This method sets or returns the value of form fields. The value of an input is
for example, the value of the value attribute in an <input>. Example: Let’s print
in the console what we provided under the value attribute for our <input>
console.log($("input").val());
</form>
<div>
<ul>
</ul>
</div>
$(document).ready(function () {
});
• parents(): returns all ancestor elements of the selected element
o Example: Let’s style all ancestor elements of our <li>
<div>
<ul>
</ul>
</div>
<div>
<p>div is my dad</p>
<ul>
</ul>
</div>
$(document).ready(function () {
});
• find(): returns descendant elements of the selected element
o Example: Let’s find only the <li> descendants of our <div> and
style them
<div>
<p>div is my dad</p>
<ul>
</ul>
</div>
<div>
<p>div is my dad</p>
<ul>
</ul>
</div>
• Looping through elements: Earlier we said that jQuery returns an object (array-like
collection) when we create a new element or select an existing element using jQuery. Using
jQuery to loop through elements is simplified way better than vanilla JavaScript. jQuery
does the looping behind the scene. Let’s compare the code will use if we want to change
the background color of all <li> elements using vanilla JavaScript and jQuery.
▪ Assume you have the following HTML
<ul>
</ul>
allLi.style.backgroundColor = "pink";
}
▪ Example of looping through elements using jQuery
$("li").css("background-color", "pink")
});
▪ Bind multiple events to one event handler
• Example: Let’s trigger the same handler function whenever the mouse
hovers over or leaves our <div>
});
$("div").on({
click: function () {
console.log("clicking div");
},
mouseenter: function () {
$("div").css("background-color", "yellow");
},
mouseleave: function () {
},
});
• Other most popular jQuery event methods:
▪ UI/DOM element events: focus, blur, change
• blur(): This method triggers the blur event or attaches a function when
blur event occurs. Blur event occurs when an element loses focus.
Example: Let’s alert a text and also change the input’s background color
to red when the <input> loses focus because user moved away the pointer
from it.
$("input").blur(function () {
$("input").css("background-color", "red");
});
▪ Keyboard events:
• keypress(): This method attaches a function to run when a keypress event
occurs. Note: keypress event is not fired for all keys (Ex. ALT, CTRL,
SHIFT, ESC). Example:
$("input").keypress(function () {
$("label").css("background-color", "pink");
});
▪ Mouse events: click, dbclick, mouseenter, mouseleave
• click(): The click() method attaches an event handler function to an HTML
element when the user clicks on the HTML element. Example: Let’s make
a <div> hide when <p> is clicked
$("p").click(function(){
$(“div”).hide();
});
$("form").on("submit", backgroundChanger);
function backgroundChanger() {
$("#firstInput").css("background-color", "pink");
$(document).ready(function(){
});
▪ Please refer this link to find the list of all jQuery event methods:
• https://www.w3schools.com/jquery/jquery_ref_events.asp
10.8 Effects and animations in jQuery
• One of the advantages of jQuery is, it lets us easily enhance our web pages by adding some
transition and movement effects
▪ Some of the popular jQuery effects: hide(), show(), toggle()
• toggle(): The toggle() method is used to check the visibility of selected
elements to toggle between hide() and show() for the selected elements.
Note: We can pass speed in milliseconds for the toggle effects. In the
following example paragraph element will take 2000 milliseconds time to
get hidden and displayed completely. Example: Let’s hide and show our
<p> with “thirdPar” id name when we click our <p> that has an id of
“firstPar”. It will take 1000 milliseconds for the <p> to hide or show upon
click
$("p#firstPar").on("click", function () {
$("p#thirdPar").toggle(1000);
});
$("#myButton").click(function () {
$("#thirdPar").slideUp(3000);
});
• slideDown(): This method slides (gradually hides) an element down.
Example: Let’s slide our <p> up with id of “thirdPar” when a button is
clicked
$("#myButton").click(function () {
$("#thirdPar").slideUp(3000);
});
<p>Hello there!</p>
$("button").click(function () {
$("p").slideToggle(3000);
});
$("#myButton).click(function () {
$("#firstPar").fadeOut();
$("#secondPar").fadeOut("slow");
$("#thirdPar").fadeOut(3000);
});
$("#myOhterButton").click(function () {
$("#thirdPar").fadeIn(1000);
});
<p>Hello there!</p>
$("button").click(function () {
$("p").delay(3000).slideToggle();
});
• animate(): This method makes the CSS property value change gradually
to create an animation effect. Note: Only CSS properties with numerical
values (such as padding: 15px) can be animated, unless we want the
animation to be between “hide” and “show” or “toggle”. Example: Let’s
add animation on our <p> by changing the already existing CSS width,
height and background color when the <button> is clicked.
$("button").click(function () {
$("p").css("background-color", "blue");
});
$("#button1").click(function () {
$("p").slideUp(3000);
});
$("#button2").click(function () {
});
10.9 Conclusion
• jQuery is just a JavaScript library that you include on your web page. As jQuery is
built on top of JavaScript, it provides all the functionalities of JavaScript. It is important
to know that jQuery is an enhanced version of JavaScript.
• jQuery makes DOM manipulation and event handling much simpler as opposed to
vanilla JavaScript. It also comes in handy when we want to include animation and
effects on our website/application. Moreover, jQuery takes a lot of common tasks that
require many lines of vanilla JavaScript code to accomplish and wraps them into
methods that you can call with a single line of code.
• Unlike vanilla JavaScript, jQuery provides a consistent result throughout major
browsers and is therefore cheered for its cross-browser compatibility.