Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

26 March 2021

JQuery
 jQuery is a lightweight, "write less, do more", JavaScript library.
 The purpose of jQuery is to make it much easier to use JavaScript on
your website.
JQuery  jQuery takes a lot of common tasks that require many lines of JavaScript code
to accomplish, and wraps them into methods that you can call with a single
line of code.
Dr.V.Mareeswari  jQuery also simplifies a lot of the complicated things from JavaScript,
like AJAX calls and DOM manipulation.
Assistant Professsor(Sr)
 The jQuery library contains the following features:
School of Information Technology and Engineering  HTML/DOM manipulation
VIT,Vellore  CSS manipulation
Cabin No:SJT 210-A30  HTML event methods
 Effects and animations
 AJAX
2  Utilities
Dr. V.Mareeswari / AP(Sr) / SITE / VIT

 Adding jQuery to Your Web Pages


 There are several ways to start using jQuery on your web site. You can:
Why jQuery?  Download the jQuery library from jQuery.com
 Include jQuery from a CDN, like Google
 There are lots of other JavaScript frameworks out there, but jQuery
 Downloading jQuery
seems to be the most popular, and also the most extendable.
 There are two versions of jQuery available for downloading:
 Many of the biggest companies on the Web use jQuery, such as:  Production version - this is for your live website because it has been minified and
 Google compressed
 Development version - this is for testing and development (uncompressed and
 Microsoft readable code)
 IBM <head>
 Netflix <script src="jquery-3.3.1.min.js"></script>
</head>
 jQuery will run exactly the same in all major browsers.  Do you wonder why we do not have type="text/javascript"
inside the <script> tag?
This is not required in HTML5. JavaScript is the default scripting language in
HTML5 and in all modern browsers!

3 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 4 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 1


26 March 2021

jQuery CDN
jQuery Syntax
 If you don't want to download and host jQuery yourself, you can include it
from a CDN (Content Delivery Network).  The jQuery syntax is tailor-made for selecting HTML elements and
 Both Google and Microsoft host jQuery.
performing some action on the element(s).
 Google CDN:  Basic syntax is: $(selector).action()
 A $ sign to define/access jQuery
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jq
uery.min.js"></script></head>  A (selector) to "query (or find)" HTML elements

 Microsoft CDN:  A jQuery action() to be performed on the element(s)

<head><script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-  Examples:


jQuery uses CSS syntax
3.3.1.min.js"></script></head>  $(this).hide() - hides the current element. to select elements.
 One big advantage of using the hosted jQuery from Google or  $("p").hide() - hides all <p> elements.
Microsoft:  $(".test").hide() - hides all elements with class="test".
Many users already have downloaded jQuery from Google or Microsoft when
 $("#test").hide() - hides the element with id="test".
visiting another site. As a result, it will be loaded from cache when they visit
your site, which leads to faster loading time. Also, most CDN's will make sure
that
5 once a user requests
Dr. V.Mareeswari a /file
/ AP(Sr) / SITE VIT from it, it will be served from the server closest 6 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

to them, which also leads to faster loading time.

The Document Ready Event jQuery Selectors


 It is good practice to wait for the document to be fully loaded and
jQuery selectors are used to "find" HTML elements based on their name, id,
classes, types, attributes, values of attributes and much more. It's based on the
ready before working with it. This also allows you to have your existing CSS Selectors, and in addition, it has some own custom selectors. All
JavaScript code before the body of your document, in the head selectors in jQuery start with the dollar sign and parentheses: $().
section. The element Selector
The jQuery element selector selects elements based on the element
 Here are some examples of actions that can fail if methods are run name.You can select all <p> elements on a page like this: $("p")
before the document is fully loaded: The #id Selector
 Trying to hide an element that is not created yet The jQuery #id selector uses the id attribute of an HTML tag to find
the specific element. An id should be unique within a page, so you should use
 Trying to get the size of an image that is not loaded yet the #id selector when you want to find a single, unique element. To find an
 Tip: The jQuery team has also created an even shorter method for element with a specific id, write a hash character, followed by the id of the
HTML element:$("#test")
the document ready event:
The .class Selector
$(document).ready(function() $(function(){ The jQuery class selector finds elements with a specific class. To find
{ // jQuery methods go here... elements with a specific class, write a period character, followed by the name of
// jQuery methods go here... }) the class: $(".test")
7 })Dr. V.Mareeswari / AP(Sr) / SITE / VIT 8 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 2


26 March 2021

Example – element selector Example – id selector


<html><head> <html><head><script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> js"></script><script>
</script><script> $(document).ready(function(){
$(document).ready(function(){ $("button").click(function(){
$("button").click(function(){
$("#test").hide();
$("p").hide();
});
}); Demo
});
});
</script></head><body>
</script></head><body>
<h2>This is a heading</h2><p>This is a paragraph.</p> <h2>This is a heading</h2>
<p>This is another paragraph.</p><button>Click me</button> <p>This is a paragraph.</p>
</body></html> <p id="test">This is another paragraph.</p>
<button>Click me</button></body></html>
9 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 10 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Example – class selector jQuery Event Methods


<html> <head> <script
 All the different visitor's actions that a web page can respond to are
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.
js"></script><script> called events.
$(document).ready(function(){  An event represents the precise moment when something happens.
$("button").click(function(){ "The keypress event is fired, the moment you press a key".
$(".test").hide();
});
});
</script></head><body>
<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button></body></html>
11 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 12 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 3


26 March 2021

<html><head><script
Event Methods src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.
 click()-The function is executed when the user clicks on the HTML
element. js"></script>
 dblclick()-The function is executed when the user double-clicks on the <script>
HTML element
$(document).ready(function(){
 mouseenter()-The function is executed when the mouse pointer enters
the HTML element $("#p1").mouseenter(function(){
 mouseleave()-The function is executed when the mouse pointer leaves the alert("You entered p1!");
HTML element
 mousedown()-The function is executed, when the left, middle or right });
mouse button is pressed down, while the mouse is over the HTML element }); </script></head><body>
 mouseup()-The function is executed, when the left, middle or right mouse
button is released, while the mouse is over the HTML element <p id="p1">Enter this paragraph.</p></body></html>
 hover()-takes two functions and is a combination of the mouseenter() and
mouseleave() methods
 focus()-The function is executed when the form field gets focus
 blur()-The function is executed when the form field loses focus Demo
 on()-method attaches one or more event handlers for the selected elements
14 Dr. V.Mareeswari / AP(Sr) / SITE / VIT
13 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

<html><head><script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">< jQuery Effects - Hide and Show Demo

/script><script> $("#hide").click(function(){
$(document).ready(function(){ $("p").hide();
$("p").on({ });
mouseenter: function(){
$(this).css("background-color", "lightgray"); }, $("#show").click(function(){
mouseleave: function(){ $("p").show();
$(this).css("background-color", "#00FF00"); },
});
click: function(){
$(this).css("background-color", "yellow"); } });}); $("button").click(function(){
</script></head><body><p>Click or move the mouse pointer over this
$("p").hide(1000);
paragraph. <br> I am Prof. Mareeswari V<br>SITE, VIT, });
Vellore.</p></body></html> The optional speed parameter specifies the speed of the hiding/showing,
and can take the following values: "slow", "fast", or milliseconds.
Demo

15 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 16 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 4


26 March 2021

jQuery Effects - Toggle Demo


jQuery Effects - Fading
 fadeIn() method is used to fade in a hidden element
<html> <head> <script $("button").click(function(){
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.j $("#div1").fadeIn(); Demo
$("#div2").fadeIn("slow");
s"></script> <script> $("#div3").fadeIn(3000); });
$(document).ready(function(){  fadeOut() method is used to fade out a visible element
$("button").click(function(){
$("button").click(function(){ $("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("p").toggle(); $("#div3").fadeOut(3000); });
}); });  fadeToggle() method toggles between the fadeIn() and fadeOut() methods
$("button").click(function(){
</script> </head> <body> $("#div1").fadeToggle();
<button>Toggle between hiding and showing the paragraphs</button> $("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000); });
<p>This is a paragraph with little content.</p> <p>This is another  fadeTo() method allows fading to a given opacity (value between 0 and 1)
small paragraph.</p> $("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
</body> </html> $("#div2").fadeTo("slow", 0.4);
Dr. V.Mareeswari / AP(Sr) / SITE / VIT
$("#div3").fadeTo("slow", 0.7);});
Dr. V.Mareeswari / AP(Sr) / SITE / VIT
17 18

jQuery Effects - Sliding Demo jQuery stop() Method $(selector).stop(stopAll,goToEnd);


<html><head><script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script  The jQuery stop() method is used to stop an animation or effect
><script> before it is finished.
$(document).ready(function(){
$("#flip").click(function(){  The stop() method works for all jQuery effect functions, including
$("#panel").slideDown("slow"); sliding, fading and custom animations.
});});</script> $(document).ready(function(){
<style>
#panel, #flip {
$("#flip").click(function(){
padding: 5px; $("#panel").slideDown(5000);
text-align: center; });
background-color: #e5eecc; slideDown()
border: solid 1px #c3c3c3;} $("#stop").click(function(){
slideUp()
#panel { slideToggle() $("#panel").stop();
padding: 50px; display: none;}
});});
</style></head><body> <div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div></body></html>
19 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 20 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 5


26 March 2021

<!DOCTYPE html> <html><head> <script


src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
jQuery Effects - Animation
<script> $(document).ready(function(){  The jQuery animate() method is used to create custom animations.
$("#flip").click(function(){  By default, all HTML elements have a static position, and cannot be
$("#panel").slideDown(5000); }); moved. To manipulate the position, remember to first set the CSS
$("#stop").click(function(){ position property of the element to relative, fixed, or absolute!
$("#panel").stop(); Demo
$("button").click(function(){ Demo
});});</script> <style>
$("div").animate({top: '250px'}); });
#panel, #flip {
padding: 5px; font-size: 18px; text-align: center; background-color: #555;  multiple properties can be animated at the same time
color: white; border: solid 1px yellow; border-radius: 18px; } $("button").click(function(){
#panel { padding:50px; display:none; } $("div").animate({
</style></head><body> opacity: '0.5',
<button id="stop">Stop sliding</button>
height: '150px',
<div id="flip">Click to slide down panel</div>
width: '150px‘
<div id="panel">Hello Mareeswari!</div></body></html> $(selector).animate({params},speed,callback);
Dr. V.Mareeswari / AP(Sr) / SITE / VIT
});});
21 22
Dr. V.Mareeswari / AP(Sr) / SITE / VIT

 It is also possible to define relative values (the value is then relative to  Uses Queue Functionality
the element's current value). This is done by putting += or -= in front  This means that if you write multiple animate() calls after each other,
of the value. jQuery creates an "internal" queue with these method calls. Then it
$("button").click(function(){ runs the animate calls ONE by ONE.
$("div").animate({ $("button").click(function(){
left: '250px', var div = $("div");
height: '+=150px', div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
width: '+=150px'
div.animate({height: '100px', opacity: '0.4'}, "slow");
});}); div.animate({width: '100px', opacity: '0.8'}, "slow"); });
 You can even specify a property's animation value as "show", "hide",  The example below first moves the <div> element to the right, and
or "toggle“ then increases the font size of the text.
$("button").click(function(){ $("button").click(function(){
$("div").animate({ var div = $("div");
height: 'toggle' div.animate({left: '100px'}, "slow");
});}); div.animate({fontSize: '3em'}, "slow"); });
23 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 24 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 6


26 March 2021

jQuery Callback Functions


 JavaScript statements are executed line by line. However, with effects,
the next line of code can be run even though the effect is not finished.
This can create errors. To prevent this, you can create a callback
function. A callback function is executed after the current effect is
100% finished.
Demo
 $("button").click(function(){
$("p").hide("slow", function(){ callback
alert("The paragraph is now hidden");
});});
Demo
 $("button").click(function(){
$("p").hide(1000); without callback
alert("The paragraph is now hidden");
});
25 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 26 Dr. V.Mareeswari / AP(Sr) / SITE / VIT $(selector).hide(speed,callback);

jQuery Method Chaining jQuery DOM Manipulation


 Chaining allows us to run multiple jQuery methods (on the same  DOM = Document Object Model
element) within a single statement.
 The following example chains together the css(), slideUp(), and
The DOM defines a standard for accessing HTML and XML
slideDown() methods. The "p1" element first changes to red, then it documents:"The W3C Document Object Model (DOM) is a platform and
slides up, and then it slides down: language-neutral interface that allows programs and scripts to
<html><head><script dynamically access and update the content, structure, and style
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.j of a document."
s"></script><script>
 Three simple, but useful, jQuery methods for DOM manipulation
$(document).ready(function(){ Demo
are:
$("button").click(function(){
 text() - Sets or returns the text content of selected elements
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
 html() - Sets or returns the content of selected elements
});});</script></head><body>
<p id="p1">jQuery is fun!!</p><br><br><br> (including HTML markup)
<button>Click me</button></body></html>  val() - Sets or returns the value of form fields
27 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 28 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 7


26 March 2021

<html> <head> <script


src="https://ajax.googleapis.com/ajax/libs/jquery
/3.3.1/jquery.min.js"></script> <script>
$(document).ready(function(){
$("#btn1").click(function(){
alert("Text: " + $("#test").text()); });
$("#btn2").click(function(){
alert("HTML: " + $("#test").html()); });
$("#btn3").click(function(){
alert("Value: " + $("#t1").val()); }); Demo
});</script></head><body>
<p id="test">This is some <b>bold</b> text in a paragraph.</p>
<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>
<p>Name: <input type="text" id="t1" value="Mickey Mouse"></p>
Dr. V.Mareeswari / AP(Sr) / SITE / VIT Dr. V.Mareeswari / AP(Sr) / SITE / VIT
<button
29 id="btn3">Show Value</button></body></html> 30

 The jQuery attr() method is used to get attribute values.


Display JSON data in Table Format
 The following example demonstrates how to get the value of the href <html><head><script
attribute in a link: src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html><head><script <style> #mytable,td{ border:1px solid blue;}</style> <script>
$(document).ready(function () {
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.j
var obj=[ { item : "001", name : "apple", category : "fruit", color : "red" },
s"></script><script>
{ item : "002", name : "melon", category : "fruit", color : "green" },
$(document).ready(function(){ { item : "003", name : "banana", category : "fruit", color : "yellow" } ]
$("button").click(function(){ var tbl=$("<table/>").attr("id","mytable");  table creation at dynamically
alert($("#w3s").attr("href")); $("#div1").append(tbl);
for(var i=0;i<obj.length;i++) { var tr="<tr>";
});});
var td1="<td>"+obj[i]["item"]+"</td>";
</script></head><body> Demo
var td2="<td>"+obj[i]["name"]+"</td>";
Demo

<a href="https://www.w3schools.com" id="w3s"> var td3="<td>"+obj[i]["color"]+"</td></tr>";


W3Schools.com</a> $("#mytable").append(tr+td1+td2+td3); }}) </script> </head><body>
<button>Show href Value</button></body> <div id="div1"> </div></body></html>
31 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 32 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 8


26 March 2021

Remove Elements
 $("#div1").remove();
 $("#div1").empty();
Demo
 $("p").remove(".test,.demo");

33 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 34 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Demo
Adding Text
 $("p").append(" <b>Appended text</b>.");
 $("ol").append("<li>Appended item</li>");
 $("p").prepend("<b>Prepended text</b>. ");
 $("ol").prepend("<li>Prepended item</li>");
 $("img").before("<b>Before</b>");
 $("img").after("<i>After</i>");
.append(): This function Insert the
 var txt3 = document.createElement("p"); data or content inside an element at last
 txt3.innerHTML = "This is paragraph text"; index.
.after(): This function puts the
element after the specified element.
35 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 36 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 9


26 March 2021

map() method
 The map() method creates a new array with the results of calling a
function for every array element.
 The map() method calls the provided function once for each
element in an array, in order.
 Note: map() does not execute the function for array elements
without values.
 Note: this method does not change the original array.
jQuery.map( array/object, callback )
 array/object: This parameter holds the Array or object to
Demo translate.
 callback: This parameter holds the function to process each item
against.

37 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 38 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

<!DOCTYPE html> <!DOCTYPE html><html><body>


<p>Click the button to get a new array with the full name of each person in the
<html> <body> array.</p>
<p>Click the button to get the square root of each element in the <button onclick="myFunction()">Try it</button>
array.</p> <p>New array: <span id="demo"></span></p>
<button onclick="myFunction()">Try it</button> <script>
<p id="demo"></p> var persons = [
<script> {firstname : "Marees", lastname: "wari"},
{firstname : "Kaylee", lastname: "Frye"},
var numbers = [4, 9, 16, 25]; {firstname : "Jayne", lastname: "Cobb“}];
function myFunction() { function getFullName(item) {
x = document.getElementById("demo") var fullname = [item.firstname,item.lastname].join(" ");
x.innerHTML = numbers.map(Math.sqrt); return fullname;}
} function myFunction() {
document.getElementById("demo").innerHTML =
</script></body></html> persons.map(getFullName);}
</script></body></html>
39 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 40 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 10


26 March 2021

EXERCISE
1. Use a jQuery method to hide the <p> element when it is clicked
on.
2. Use a jQuery method to hide the <p> element when it is clicked
on. The speed should be "slow".
3. There is a hidden <p> element in the document. Use a jQuery
method to show the <p> element with a click of a button.
4. Toggle between hiding and showing the <p> element when you
click on the "Toggle" button.
5. Use a jQuery method to slide up the <div> element. The duration
of the effect should be "slow".

41 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 42 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Exercise Exercise
 Develop a quiz application using Jquery methods. The application  Use jQuery selectors to identify elements with these
should be developed in such a way that after the user attempted a properties in a hypothetical page:
quiz question, the answer along with the explanation should be  All p tags that have no children, but only if they don't have a
displayed when the user clicks the answer button. Use sliding class of ignore
methods to develop the same.  Any element with the text "REPLACE_ME" in it.
 Develop a animated application using Jquery, the application  All div tags with a child that has a class of special
should be developed in such a way that the user pressed the  All heading elements (h1, h2, h3, h4, h5, h6)
button, the object along with text should be move from left to  Every other visible li. Use the DOM API to target the
right, right to left , top to bottom and bottom to top with #square and periodically change it's position in a random
particular set of intervals after completing the task it should be direction.
hide.  Use jQuery selectors instead of the DOM API.

43 Dr. V.Mareeswari / AP(Sr) / SITE / VIT 44 Dr. V.Mareeswari / AP(Sr) / SITE / VIT

Dr.V.Mareeswari / AP(Sr) / SITE 11

You might also like