DOC_LM_unit2 (3)
DOC_LM_unit2 (3)
What is jQuery?
▪ JQuery is a lightweight, "write less, do more", fast JavaScript library.
▪ To perform any task, jQuery requires less code as compared to JavaScript.
▪ It is platform independent (cross platform) and supports different types of browsers.
▪ The purpose of jQuery is to make it much easier to use JavaScript on your website.
▪ It is also very useful to simplify a lot of the complicated things from JavaScript, like AJAX calls
and DOM manipulation.
▪ It makes things like HTML document traversal and manipulation, animation, event handling,
and AJAX very simple with an easy-to-use API that works on a lot of different type of browsers.
(jQuery simplifies AJAX call and DOM manipulation)
▪ JQuery was first released in January 2006 by John Resig at BarCamp NYC.
Why JQuery is required?
▪ There are lots of other JavaScript libraries out there, but jQuery is probably the most
popular, and also the most extendable.
▪ It is very fast and extensible.
▪ It facilitates the users to write UI related function codes in minimum possible lines.
▪ It improves the performance of an application.
▪ Browser's compatible web applications can be developed.
▪ It uses mostly new features of new browsers.
▪ Many of the biggest companies on the Web use jQuery, such as:
- Google, Microsoft, IBM, Netflix
Advantages of jQuery
▪ Simple and Easy: It has predefined method through which you can perform any task easily
as compare to JavaScript. And it is easy to learn.
▪ It is very lightweight library - about 19KB in size.
▪ Write less do more: jQuery provides a rich set of features that increase developers'
productivity by writing less and readable code.
▪ It basically creates a jQuery object and evaluates the expression passed as its parameters.
It then determines how it should respond and modifies itself accordingly.
JQuery Syntax
▪ The jQuery syntax is tailor-made
for selecting HTML elements and
performing some action on the
element(s).
Syntax: $(selector).action();
o A $ sign to define/access
jQuery
o A (selector) to "query (or find)"
HTML elements
o A jQuery action() to be
performed on the element(s)
Examples:
o $(this).hide() - hides the current element.
o $("p").hide() - hides all <p> elements.
o $(".test").hide() - hides all elements with class="test".
o $("#test").hide() - hides the element with id="test".
jQuery Selectors
▪ jQuery selectors are one of the most important aspects of the jQuery library.
▪ These selectors use familiar CSS syntax to allow page authors to quickly and easily identify
any set of page elements to operate upon with the jQuery library methods.
▪ Understanding jQuery selectors is the key to using the jQuery library most effectively.
▪ A jQuery selector selects the HTML elements on a variable parameter such as their name,
classes, id, types, attributes, attribute values, etc.
▪ Once an element is selected then we can perform various operations on that selected
element.
▪ jQuery selectors start with the dollar sign and parentheses − $().
▪ The selector is a string expression that identifies the set of DOM elements that will be
collected into a matched set to be operated upon by the jQuery methods.
Elements Selectors
▪ The elements selector selects the element on the basis of its name.
▪ There are two ways to select multiple elements using selectors:
o Element selector
Syntax:$("element1, element2, element3, ...")
o * selector - to select all elements
Syntax:$("*")
Id Selector:
▪ The id selector selects the element on the basis of its id.
Syntax: $("#id") id represents the element’s specific id.
▪ To have multiple Id selectors, Select the ID’s of different element and then use each()
method to apply the CSS property on all selected ID’s element.
Syntax: $("#id1, #id2, #id3, ...")
<html>
<head>
<title>The jQuery Example</title>
<body>
<div>
<p id = "myid">This is first paragraph.</p>
</div>
<p id = "myid1">This is second paragraph.</p>
<p id = "myid2">This is third paragraph.</p>
<script type = "text/javascript">
$(document).ready(function() {
$("#myid").css("background-color", "yellow");
$("#myid1,#myid2").css("background-color", "red");
});
</script>
</body>
</html>
▪ When the above page is run in browser, it displays,
Class Selector:
▪ The class selector selects the element on the basis of its class.
Syntax: $(".class")
▪ To select multiple classes, we use the following syntax:
$(".class1, .class2, .class3, ...")
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
</head>
<body>
<div class = "myclass">
This is first paragraph.
</div>
<p class = "myclass1">This is second paragraph.</p>
<p class = "myclass2">This is third paragraph.</p>
<script type = "text/javascript">
$(document).ready(function() {
$(".myclass").css("color", "red");
$(".myclass1,.myclass2").css("background-color", "orange");
});
</script>
</body>
</html>
▪ When the above page is run in browser, it displays,
‘*’ Selector:
▪ The jQuery * selector selects all the elements in the document, including HTML, body, and
head.
▪ If the * selector is used together with another element then it selects all child elements
within the element used.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript" src="jquery/2.1.3/jquery.min.js">
</script>
</head>
<body>
<div class = "myclass">
This is first paragraph.
</div>
<p class = "myclass1">This is second paragraph.</p>
<p class = "myclass2">This is third paragraph.</p>
<script type = "text/javascript">
$(document).ready(function() {
$("*").css("color", "red");
$(".myclass1,.myclass2").css("background-color", "orange");
});
</script>
</body>
</html>
Multiple Selector (“selector1, selector2, selectorN”):
Note:
▪ If dealing with more than two selectors in a row then our last selectors are always executed
first.
$('p').html($("second.list").text());
For example, jQuery will first find all the elements with class “.list” and then it will select all the
elements with the id “second”.
Example of Selectors
class,.class $(".primary,.secondary") It will select all elements with the class "primary"
or "secondary"
[attribute=value] $("[href='default.htm']") Select all elements with a href attribute value equal
to "default.htm"
[attribute!=value] $("[href!='default.htm']") It will select all elements with a href attribute value
not equal to "default.htm"
JQuery Events
▪ In most web applications, the user does some action to perform an operation. For example,
user clicks on save button to save the edited data in a web page. Here, clicking on the
button is a user's action, which triggers click event and click event handler (function) saves
data.
▪ In some cases, the Browser itself can trigger the events, such as the page load and unload
events.
▪ In the example below, a function is called when the click event for the button is triggered:
▪ Example
<!DOCTYPE html> <html> <head> <script src="jquery.js"></script> <script>
$(document).ready(function()
{ $("button").click(function()
{ $("p").hide(); }); });
</script>
</head>
<body>
<p>This is paragraph.</p>
<button>Click me</button> </body>
</html>
Some jQuery Event Methods
Here are some examples of event
methods in jQuery:
▪ The keypress() method triggers the keypress event, or attaches a function to run when a
keypress event occurs.
o keydown - The key is on its way down
o keypress - The key is pressed down
o keyup - The key is released
Syntax:
$(selector).keypress() OR $(selector).keypress(function)
Ex:
<html>
<head>
<script src="jquery/2.1.3/jquery.min.js"></script>
<script>
i = 0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text(i += 1);
});
});
</script>
</head>
<body>
Enter your name: <input type="text">
<p>Keypresses: <span>0</span></p>
</body>
</html>
▪ The above code when executed calculates the no. of keys that have been pressed.
jQuery focus()
▪ The focus event occurs when an element gets focus (when selected by a mouse click or by
"tab-navigating" to it).
▪ The focus() method triggers the focus event, or attaches a function to run when a focus event
occurs.
Syntax:
$(selector).focus(function)
Ex:
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$("span").css("display", "inline").fadeOut(2000);
});
});
</script>
<style>
span { display: none;}
</style>
</head>
<body>
<input><span>Nice to meet you!</span>
<p>Click in the input field to get focus.</p>
</body>
</html>
jQuery blur()
▪ The blur() is an inbuilt method is jQuery that is used to remove focus from the selected
element.
▪ This method start the blur event or it can be attached a function when a blur event occurs.
Syntax:
$(selector).blur() or $(selector).blur(function)
Ex:
<html>
<head>
<script src="jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").blur(function(){
$(this).css("background-color", "#ffeeff"); });
});
</script>
</head>
<body>
Enter your name: <input type="text">
</body></html>
jQuery 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.
Syntax:
$(selector).change() or $(selector).change(function)
Ex:
<html>
<head>
<script src="jquery.min.js"></script>
<!--Demo of change method without passing function-->
<script>
$(document).ready(function() {
$("button").click(function() {
$("input").change();
});
});
</script>
</head>
<body>
<p>Click the button to see the changed value !!!</p>
<!--click on this button and see the change -->
<button>Click Me!</button>
<p>Enter value:
<input value="Donald" onchange="alert(this.value)"
type="text"></p>
</body>
</html>
jQuery Chaining
▪ It is possible with jQuery to get multiple sets of elements and do multiple things with them,
all within a single line of code.
▪ And it is also possible to break a single line of code into multiple lines for greater readability.
▪ Until now we have been writing jQuery statements one at a time (one after the other).
▪ In jQuery, there is a technique called chaining, that allows us to run multiple jQuery methods
or actions, one after the other, on the same element(s).
▪ Due to Chaining, browsers do not have to find the same element(s) more than once.
▪ To chain an action, we simply append the action to the previous action.
Ex.
$("#p1").css("background-color", "red").slideUp(2000).slideDown(2000);
▪ The above statement applies background color red to paragraph and at the same time also
applies slide down and slide up effects.
▪ We can also give line breaks or indentations in chaining as jQuery ignores all whitespaces
when giving breaks.
JQuery Stop()
The jQuery stop() method is used to stop an animation or effect before it is finished.
The stop() method works for all jQuery effect functions, including sliding, fading and custom
animations.
Syntax:
$(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the animation queue should be cleared or
not. Default is false, which means that only the active animation will be stopped, allowing any
queued animations to be performed afterwards.
The optional goToEnd parameter specifies whether or not to complete the current animation
immediately. Default is false.
So, by default, the stop() method kills the current animation being performed on the selected
element.
The following example demonstrates the stop() method, with no parameters:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
font-size: 18px;
text-align: center;
background-color: #555;
color: white;
border: solid 1px #666;
border-radius: 3px;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
</body>
</html>
jQuery Callback
▪ A callback function is executed after the current effect of current method or action is
completely finished.
▪ Normally jquery statements execute sequentially. But when we give effects or animation with
timings the next statements start to execute even though the effect is yet not completely
applied on the element.
▪ To avoid such situations where errors might arise, we use callback functions.
Syntax:
$(selector).hide(speed,callback);
▪ Thus, in order to allow queuing effects on different elements, jQuery provides callback
functions.
▪ In event handlers, callbacks are simply functions passed as method arguments.
▪ In the case of effects, they will usually appear as the last argument of the method.
<html lang="en">
<head>
<script src= "jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("p").slideHide("fast",
function callback() {
<body>
<p>CKPCMC</p>
<button id="b" type="button">Hide the Div</button>
</body>
Method Description
attr() Get or set the value of specified attribute of the target element(s).
html() Get or set html content to the specified target element(s).
text() Get or set text for the specified target element(s).
val() Get or set value property of the specified target element.
attr()
▪ The attr() method sets or returns attributes and values of the selected elements.
▪ Syntax:
$('selector expression').attr('name','value');
▪ We specify a selector to get the reference of an element and call attr() method with attribute
name parameter.
▪ To set the value of an attribute, pass value parameter along with name parameter.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").attr("width", "500");
});
});
</script>
</head>
<body>
<img src="img_pulpitrock.jpg" alt="Pulpit Rock" width="284" height="213"><br>
<button>Set the width attribute of the image</button>
</body>
</html>
Set the width attribute of an image:
val()
▪ The val() method returns or sets the value attribute of the selected elements.
▪ This method returns the value of an input, or if a value is supplied, sets the value of an input.
▪ When used to return value: This method returns the value of the value attribute of the FIRST
matched element.
Syntax:
$(selector).val()
▪ When used to set value: This method sets the value of the value attribute for ALL matched
elements.
$(selector).val(value)
Ex:
<html>
<head>
<script src=”jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input:text").val("raju");
});
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>
text()
• The text() method sets or returns the text content of the selected elements.
• Syntax:
$(selector).text()
Ex:
<html>
<head>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text("Hello world!");
});
});
</script>
</head>
<body>
<button>Set text content for all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
html()
▪ When dealing with the contents of an element, the .text() and .html() methods are used.
▪ The difference between the two is that .html()will allow us to read out and insert new HTML
tags into an element, where .text() is for reading and writing text only.
▪ If either of these methods is called on an element set with no arguments, the contents of the
element are returned.
▪ When a value is passed to the method, the existing value is overwritten, and the new value is
put in its place.
• The html() method sets or returns the content (innerHTML) of the selected elements.
• When this method is used to return content, it returns the content of the matched
element.
• When this method is used to set content, it overwrites the content of ALL matched
elements.
• Syntax:
$(selector).html() or $(selector).html(content)
Ex:
<html>
<head>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").html("Hello <b>world!</b>");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
append() in jQuery
▪ The .append() and .prepend() functions will attach the elements passed as arguments to the
jQuery object to which they are chained. The only difference is that .append() attaches the
elements at the end, and .prepend() attaches at the beginning.
▪ This append() Method in jQuery is used to insert some content at the end of the selected
elements.
Syntax:
$(selector).append( content, function())
$(selector).prepend( content, function())
▪ Parameters: This method accepts two parameters as mentioned above and described below:
▪ content: It is required parameter and used to specify the content which is to be inserted at
the end of selected elements. The possible values of contents are HTML elements, jQuery
objects and DOM elements.
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Append Geeks</b>.");
});
$("#btn2").click(function(){
$("ol").prepend("<li>Prepend Gfg</li>");
});
});
</script>
<body>
<h1 style="margin-left: 150px;">Geeks</h1>
<p>GeeksforGeeks</p>
<p>Jquery</p>
<ol>
<li>Gfg 1</li><li>Gfg 2</li><li>Gfg 3</li>
</ol>
$(selector).before (content)
$(selector).after (content)
▪ The reverse of the after() method is before() method, which inserts the content before
the selected HTML element.
<script>
$( document).ready( function(){
$( "button" ).click( function(){
$("h1").before ("<p><b>This content is inserted by before method. </b></p>");
$("h1").after("<b><p> This content is inserted by after method. </b></p>");
});
});
</script>
JQuery Wrap()
▪ The wrap() method wraps specified HTML element(s) around each selected element.
Syntax:
$(selector).wrap(wrappingElement)
▪ wrappingElement ▪ Required. Specifies what HTML element(s) to wrap
around each selected element
▪ Possible values:
▪ HTML elements
▪ jQuery objects
▪ DOM elements
JQuery unwrap()
The unwrap() method removes the parent element of the selected elements.
Syntax:
$(selector).unwrap()
Ex:
<html>
<head>
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").wrap("<div></div>");
});
$("#btn2").click(function(){
$("p").unwrap();
});
});
</script>
<style>
div{background-color: yellow;}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button id="btn1">Wrap a div element around each p element</button>
<button id="btn2">Unwrap</button>
</body>
</html>
jQuery css()
The jQuery CSS() method is used to get (return)or set style properties or values for selected
elements. It facilitates you to get one or more style properties.