1.JQuery Notes
1.JQuery Notes
jQuery tutorial for beginners and professionals provides deep knowledge of jQuery
technology. Our jQuery tutorial will help you to learn jQuery fundamentals, example,
selectors, events, effects, traversing, CSS and attributes.
What is jQuery
o jQuery is a small and lightweight JavaScript library.
o jQuery is cross-platform.
o jQuery means "write less do more".
o jQuery simplifies AJAX call and DOM manipulation.
jQuery Example
In this tutorial, you will get a lot of jQuery examples to understand the topic well. Let's see
a simple jQuery example.
File: firstjquery.html
<!DOCTYPE html>
<html>
<head>
<title>First jQuery Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.m
in.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("p").css("background-color", "pink");
});
</script>
</head>
<body>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
</body>
</html>
Output:
This is first paragraph.
jQuery
jQuery is a fast, small, cross-platform and feature-rich JavaScript library. It is designed to
simplify the client-side scripting of HTML. 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.
The main purpose of jQuery is to provide an easy way to use JavaScript on your website to
make it more interactive and attractive. It is also used to add animation.
What is jQuery
jQuery is a small, light-weight and fast JavaScript library. It is cross-platform and supports
different types of browsers. It is also referred as ?write less do more? because it takes a lot
of common tasks that requires many lines of JavaScript code to accomplish, and binds them
into methods that can be called with a single line of code whenever needed. It is also very
useful to simplify a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.
jQuery Features
Following are the important features of jQuery.
o HTML manipulation
o DOM manipulation
o DOM element selection
o CSS manipulation
o Effects and Animations
o Utilities
o AJAX
o HTML event methods
o JSON Parsing
o Extensibility through plug-ins
So, you can say that out of the lot of JavaScript frameworks, jQuery is the most popular and
the most extendable. Many of the biggest companies on the web use jQuery.
o Microsoft
o Google
o IBM
o Netflix
jQuery Example
jQuery is developed by Google. To create the first jQuery example, you need to use
JavaScript file for jQuery. You can download the jQuery file from jquery.com or use the
absolute URL of jQuery file.
In this jQuery example, we are using the absolute URL of jQuery file. The jQuery example is
written inside the script tag.
File: firstjquery.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>First jQuery Example</title>
5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.
1.3/jquery.min.js">
6. </script>
7. <script type="text/javascript" language="javascript">
8. $(document).ready(function() {
9. $("p").css("background-color", "cyan");
10. });
11. </script>
12. </head>
13. <body>
14. <p>The first paragraph is selected.</p>
15. <p>The second paragraph is selected.</p>
16. <p>The third paragraph is selected.</p>
17. </body>
18. </html>
Output:
1. $(document).ready(function() {
2. $("p").css("color", "red");
3. });
1. $(function() {
2. $("p").css("color", "red");
3. });
Let's see the full example of jQuery using shorthand notation $().
File: shortjquery.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Second jQuery Example</title>
5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.
1.3/jquery.min.js">
6. </script>
7. <script type="text/javascript" language="javascript">
8. $(function() {
9. $("p").css("color", "red");
10. });
11. </script>
12. </head>
13. <body>
14. <p>The first paragraph is selected.</p>
15. <p>The second paragraph is selected.</p>
16. <p>The third paragraph is selected.</p>
17. </body>
18. </html>
Output:
jQuery Selectors
jQuery Selectors are used to select and manipulate HTML elements. They are very important part of
jQuery library.
With jQuery selectors, you can find or select HTML elements based on their id, classes, attributes, types
and much more from a DOM.
In simple words, you can say that selectors are used to select one or more HTML elements using jQuery
and once the element is selected then you can perform various operation on that.
All jQuery selectors start with a dollor sign and parenthesis e.g. $(). It is known as the factory function.
Let's take a simple example to see the use of Tag selector. This would select all the elements with a tag
name
and the background color is set to "pink".
File: firstjquery.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>First jQuery Example</title>
5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.j
s">
6. </script>
7. <script type="text/javascript" language="javascript">
8. $(document).ready(function() {
9. $("p").css("background-color", "pink");
10. });
11. </script>
12. </head>
13. <body>
14. <p>This is first paragraph.</p>
15. <p>This is second paragraph.</p>
16. <p>This is third paragraph.</p>
17. </body>
18. </html>
Output:
parent > child $("div > p") It will select all p elements that
are a direct child of a div element
jQuery Effects
jQuery enables us to add effects on a web page. jQuery effects can be categorized into fading, sliding, hiding/showing
and animation effects.
jQuery hide()
OutPut:-
This is a little poem:
Twinkle, twinkle, little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle, twinkle little star
How I wonder what you are
jQuery show()
The jQuery show() method is used to show the selected elements.
Syntax:
1. $(selector).show();
2. $(selector).show(speed, callback);
3. $(selector).show(speed, easing, callback);
speed: It is an optional parameter. It specifies the speed of the delay. Its possible vales
are slow, fast and milliseconds.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<p>
<b>This is a little poem: </b><br/>
Twinkle, twinkle, little star<br/>
How I wonder what you are<br/>
Up above the world so high<br/>
Like a diamond in the sky<br/>
Twinkle, twinkle little star<br/>
How I wonder what you are
</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
OutPut:-
This is a little poem:
Twinkle, twinkle, little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle, twinkle little star
How I wonder what you are
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide(1000);
});
$("#show").click(function(){
$("p").show(1500);
});
});
</script>
</head>
<body>
<p>
<b>This is a little poem: </b><br/>
Twinkle, twinkle, little star<br/>
How I wonder what you are<br/>
Up above the world so high<br/>
Like a diamond in the sky<br/>
Twinkle, twinkle little star<br/>
How I wonder what you are
</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
OutPut:-
This is a little poem:
Twinkle, twinkle, little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle, twinkle little star
How I wonder what you are
jQuery toggle()
The jQuery toggle() is a special type of method which is used to toggle between the hide()
and show() method. It shows the hidden elements and hides the shown element.
Syntax:
1. $(selector).toggle();
2. $(selector).toggle(speed, callback);
3. $(selector).toggle(speed, easing, callback);
4. $(selector).toggle(display);
speed: It is an optional parameter. It specifies the speed of the delay. Its possible vales are
slow, fast and milliseconds.
easing: It specifies the easing function to be used for transition.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div.d1").toggle();
});
});
</script>
</head>
<body>
<button>Toggle</button>
<div class="d1" style="border:1px solid black;padding:10px;width:250px">
<p><b>This is a little poem: </b><br/>
Twinkle, twinkle, little star<br/>
How I wonder what you are<br/>
Up above the world so high<br/>
Like a diamond in the sky<br/>
Twinkle, twinkle little star<br/>
How I wonder what you are</p>
</div>
</body>
</html>
jQuery toggle() effect with speed parameter
Let's see the example of jQuery toggle effect with 1500 milliseconds speed.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div.d1").toggle(1500);
});
});
</script>
</head>
<body>
<button>Toggle</button>
<div class="d1" style="border:1px solid black;padding:10px;width:250px">
<p><b>This is a little poem: </b><br/>
Twinkle, twinkle, little star<br/>
How I wonder what you are<br/>
Up above the world so high<br/>
Like a diamond in the sky<br/>
Twinkle, twinkle little star<br/>
How I wonder what you are</p>
</div>
</body>
</html>
jQuery fadeIn()
jQuery fadeIn() method is used to fade in the element.
Syntax:
1. $(selector).fadein();
2. $(selector).fadeIn(speed,callback);
3. $(selector).fadeIn(speed, easing, callback);
speed: It is an optional parameter. It specifies the speed of the delay. Its possible vales are
slow, fast and milliseconds.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
</head>
<body>
<p>See the fadeIn() method example with different parameters.</p>
<button>Click to fade in boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;display:none;background-
color:red;"></div>
<div id="div2" style="width:80px;height:80px;display:none;background-
color:green;"></div>
<div id="div3" style="width:80px;height:80px;display:none;background-
color:blue;"></div>
</body>
</html>
jQuery fadeOut()
The jQuery fadeOut() method is used to fade out the element.
Syntax:
1. $(selector).fadeOut();
2. $(selector).fadeOut(speed,callback);
3. $(selector).fadeOut(speed, easing, callback);
speed: It is an optional parameter. It specifies the speed of the delay. Its possible vales are
slow, fast and milliseconds.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
});
</script>
</head>
<body>
<p>See the fadeOut() method example with different parameters.</p>
<button>Click to fade out boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-
color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>
</body>
</html>
jQuery fadeToggle()
jQuery fadeToggle() method is used to toggle between the fadeIn() and fadeOut()
methods. If the elements are faded in, it will make them faded out and if they are faded
out it will make them faded in.
Syntax:
1. $(selector).fadeToggle();
2. $(selector).fadeToggle(speed,callback);
3. $(selector).fadeToggle(speed, easing, callback);
speed: It is an optional parameter. It specifies the speed of the delay. Its possible vales
are slow, fast and milliseconds.
jQuery fadeTo()
jQuery fadeTo() method is used to fading to a given opacity.
Syntax:
1. $(selector).fadeTo(speed, opacity);
2. $(selector).fadeTo(speed, opacity, callback);
3. $(selector).fadeTo(speed, opacity, easing, callback);
speed: It specifies the speed of the delay. Its possible vales are slow, fast and milliseconds.
opacity:It specifies the opacity. The opacity value ranges between 0 and 1.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeTo("slow", 0.3);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.5);
});
});
</script>
</head>
<body>
<p>See the fadeTo() method example with different parameters.</p>
<button>Click to fade boxes</button><br><br>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-
color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>
</body>
</html>
jQuery slideDown()
jQuery slideDown() method is used to slide down an element.
Syntax:
1. $(selector).slideDown(speed);
2. $(selector).slideDown(speed, callback);
3. $(selector).slideDown(speed, easing, callback);
speed: It specifies the speed of the delay. Its possible vales are slow, fast and milliseconds.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #00FFFF;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello javatpoint.com!
It is the best tutorial website to learn jQuery and other languages.</div>
</body>
</html>
After clicking
jQuery slideUp()
jQuery slideDown() method is used to slide up an element.
Syntax:
1. $(selector).slideUp(speed);
2. $(selector).slideUp(speed, callback);
3. $(selector).slideUp(speed, easing, callback);
speed: It specifies the speed of the delay. Its possible vales are slow, fast and milliseconds.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideUp("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #00FFFF;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
}
</style>
</head>
<body>
<div id="flip">Click to slide up panel</div>
<div id="panel">Hello javatpoint.com!
It is the best tutorial website to learn jQuery and other languages.</div>
</body>
</html>
After clicking
jQuery slideToggle()
jQuery slideToggle () method is used to toggle between slideUp() and slideDown()
method. If the element is slide down, it will slide up the element and if it is slide up, it
will slide down.
Syntax:
1. $(selector).slideToggle(speed);
2. $(selector).slideToggle(speed, callback);
3. $(selector).slideToggle(speed, easing, callback);
speed: It specifies the speed of the delay. Its possible vales are slow, fast and
milliseconds.
After clicking
jQuery animate()
The jQuery animate() method provides you a way to create custom animations.
Syntax:
1. $(selector).animate({params}, speed, callback);
The speed parameter is optional and specifies the duration of the effect. It can be set as
"slow" , "fast" or milliseconds.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '450px'});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>A simple animation example:</p>
<div
style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
jQuery animate() method using multiple properties
You can use multiple properties to animate at the same time.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<div
style="background:#125f21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
After clicking
jQuery animate() method using relative values
You can also define relative values (it is relative to the element's current value) by putting
+= or -= in front of the value.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=150px',
width: '+=150px'
});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<div
style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
After clicking
After clicking
jQuery animate() method using predefined value
You can also specify a property's animation value as "show" , "hide" , or "toggle".
In this example, we are using "toggle" value for height, it means it will show/hide the
selected element.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
height: 'toggle'
});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<div
style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
After clicking
After clicking
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Effects - Animate demo</title>
<link rel="stylesheet"
href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<style>
.toggler { width: 500px; height: 200px; position: relative; }
#button { padding: .5em 1em; text-decoration: none; }
#effect { width: 240px; height: 135px; padding: 0.4em; position: relative;
background: #fff; }
#effect h3 { margin: 0; padding: 0.4em; text-align: center; }
</style>
<script>
$(function() {
var state = true;
$( "#button" ).click(function() {
if ( state ) {
$( "#effect" ).animate({
backgroundColor: "#aa0000",
color: "#fff",
width: 500
}, 1000 );
} else {
$( "#effect" ).animate({
backgroundColor: "#fff",
color: "#000",
width: 240
}, 1000 );
}
state = !state;
});
});
</script>
</head>
<body>
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<h3 class="ui-widget-header ui-corner-all">Animate</h3>
<p>Javatpoint.com is the best tutorial website to learn Java and other
programming languages.</p>
</div>
</div>
<button id="button" class="ui-state-default ui-corner-all">Toggle Effect</button>
</body>
</html>
After clicking
After clicking
jQuery delay()
The jQuery delay() method is used to delay the execution of functions in the queue. It is a
best method to make a delay between the queued jQuery effects. The jQUery delay ()
method sets a timer to delay the execution of the next item in the queue.
Syntax:
1. $(selector).delay (speed, queueName)
speed: It is an optional parameter. It specifies the speed of the delay. Its possible vales are
slow, fast and milliseconds.
queueName: It is also an optional parameter. It specifies the name of the queue. Its
default value is "fx" the standard queue effect.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").delay("slow").fadeIn();
});
});
</script>
</head>
<body>
<button>Click me</button><br>
<div id="div1" style="width:90px;height:90px;display:none;background-
color:black;"></div><br>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").delay("fast").fadeIn();
$("#div2").delay("slow").fadeIn();
$("#div3").delay(1000).fadeIn();
$("#div4").delay(2000).fadeIn();
$("#div5").delay(4000).fadeIn();
});
});
</script>
</head>
<body>
<p>This example sets different speed values for the delay() method.</p>
<button>Click to fade in boxes with a different delay time</button>
<br><br>
<div id="div1" style="width:90px;height:90px;display:none;background-
color:black;"></div><br>
<div id="div2" style="width:90px;height:90px;display:none;background-
color:green;"></div><br>
<div id="div3" style="width:90px;height:90px;display:none;background-
color:blue;"></div><br>
<div id="div4" style="width:90px;height:90px;display:none;background-
color:red;"></div><br>
<div id="div5" style="width:90px;height:90px;display:none;background-
color:purple;"></div><br>
</body>
</html>
After clicking
jQuery html()
jQuery html() method is used to change the entire content of the selected elements. It
replaces the selected element content with new contents.
Note: It is a very useful function but works in a limited area because of its API
documentation. The API documentation of the jQuery html function consists of three
method signatures.
The first method signature has no argument, so it just returns the HTML within that
element. The remaining two signatures take a single argument: i.e. a string or a function
that returns a string.
Syntax:
1. $(selector).html()
1. $(selector).html(content)
1. $(selector).html(function (index, currentcontent))
The jQuery html() method is used either for set the content or return the content of the
selected elements.
o To set content: When you use this method to set content, it overwrites the content
of the all matched elements.
o To return content: When you use this method to return content, it returns the
content of the first matched element.
The text() method is used to set or return only the text content of the selected elements.
Parameter Description
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").html("Hello <b>Javatpoint.com</b>");
});
});
</script>
</head>
<body>
<button>Click here to change the content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
After clicking
jQuery html() example 3
Let's see another example of jQuery html() method that converts HTML to text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>html demo</title>
<style>
p{
margin: 8px;
font-size: 20px;
color: blue;
cursor: pointer;
}
b{
text-decoration: underline;
}
button {
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>
<b>Click</b> here to change the <span id="tag">html to text</span>
</p>
<script>
$( "p" ).click(function() {
var htmlString = $( this ).html();
$( this ).text( htmlString );
});
</script>
</body>
</html>
After clicking
jQuery text()
The jQuery text() method is used to set or return the text content of the selected elements.
To return content: When this method is used to return content, it returns the combined text content o
markup.
To set content: When this method is used to set content, it overwrites the content of all matched elem
o The jQuery text() method is used to set or return html content without HTML markup while, html
innerHtml (text + HTML markup).
o The jQuery text() method can be used in both XML and HTML document while jQuery html() meth
Syntax:
1. $(selector).text()
1. $(selector).text(content)
1. $(selector).text(function(index,currentcontent))
Parameter Description
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text("Welcome to javatpoint.com!");
});
});
</script>
</head>
<body>
<button>Click here to set text content for all p elements</button>
<p>Hello Guys!</p>
<p>Looking for online training....</p>
</body>
</html>
After clicking
jQuery val()
There are two usage of jQuery val() method.
o It is used to get current value of the first element in the set of matched elements.
o It is used to set the value of every matched element.
Syntax:
1. $(selector).val()
1. $(selector).val(value)
1. $(selector).val(function(index,currentvalue))
Parameter Description
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>val demo</title>
<style>
p{
color: red;
margin: 4px;
}
b{
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p></p>
<select id="single">
<option>Single</option>
<option>Double</option>
<option>Triple</option>
</select>
<script>
function displayVals() {
var singleValues = $( "#single" ).val();
$( "p" ).html( "<b>Value:</b> " + singleValues);
}
$( "select" ).change( displayVals );
displayVals();
</script>
</body>
</html>
After clicking
Let's see example of jQuery val() method with single and multiple select boxes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>val demo</title>
<style>
p{
color: red;
margin: 4px;
}
b{
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p></p>
<select id="single">
<option>Single</option>
<option>Single2</option>
<option>Single3</option>
</select>
<select id="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option>Multiple3</option>
</select>
<script>
function displayVals() {
var singleValues = $( "#single" ).val();
var multipleValues = $( "#multiple" ).val() || [];
$( "p" ).html( "<b>Single:</b> " + singleValues +
" <b>Multiple:</b> " + multipleValues.join( ", " ) );
}
$( "select" ).change( displayVals );
displayVals();
</script>
</body>
</html>
After clicking
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input:text").val("JavaTpoint");
});
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>
After clicking
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.
Syntax:
1. css("propertyname");
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style="background-color:#ff0000">The background-color of this paragraph is
red.</p>
<p style="background-color:#00ff00">The background-color of this paragraph is
green.</p>
<p style="background-color:#0000ff">The background-color of this paragraph is
blue.</p>
<button>Click here to get the background-color of first matched
element.</button>
</body>
</html>
After clicking
Syntax:
1. css("propertyname","value");
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "violet");
});
});
</script>
</head>
<body>
<p style="background-color:#ff0000">The background-color of this paragraph is
red.</</p>
<p style="background-color:#00ff00">The background-color of this paragraph is
green.</</p>
<p style="background-color:#0000ff">The background-color of this paragraph is
blue.</</p>
<p>This paragraph has no background-color. </p>
<button>Click here to set a specific background-color of all matched
element</button>
</body>
</html>
3) Set multiple CSS properties
It is just an extension of Set CSS property. It facilitates you to add multiple property values
together.
Syntax:
1. css({"propertyname":"value","propertyname":"value",...});
Let's take an example to demonstrate this property. In this example we add two properties
background-color and font-size for all element.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css({"background-color": "yellow", "font-size": "200%"});
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p style="background-color:#ff0000">The background-color of this paragraph is
red.</p>
<p style="background-color:#00ff00">The background-color of this paragraph is
green.</p>
<p style="background-color:#0000ff">The background-color of this paragraph is
blue.</p>
<p>This paragraph has no background-color.</p>
<button>Click here to set multiple styles for all selected elements.</button>
</body>
</html>
jQuery before()
The jQuery before() method is used to insert the specified content before the selected
elements. It adds the content specified by the parameter, before each element in the set of
matched elements.
The before() and insertBefore() both methods are used to perform same task. The main difference
between them is in syntax, and the placement of the content and the target.
Syntax:
1. $(selector).before(content, function(index))
Parameter Description
Function (index) It specifies a function that returns the content which is used to
insert.
o Index: It provides the index position of the element in the
set.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").before("<p><b>Hello javatpoint.com</b></p>");
});
});
</script>
</head>
<body>
<button>Insert content before each p element</button>
<p>This is a tutorial website.</</p>
<p>This is a training institute.</</p>
</body>
</html>
After clicking
jQuery prepend()
The jQuery prepend() method is used to insert the specified content at the beginning (as a
first child) of the selected elements. It is just the opposite of the jQuery append() method.
If you want to insert the content at the end of the selected elements, you should use the
append method.
Syntax:
1. $(selector).prepend(content,function(index,html))
Parameter Description
Content It is a mandatory parameter. It specifies the content which you
want to insert. Its possible values are:
o HTML elements
o jQuery objects
o DOM elements
Function (index, html) It is an optional parameter. It specifies a function that returns the
content which is inserted.
o Index:It is used to provide the index position of the
element in the set.
o Html: : It provides the current HTML of the selected
element.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend("<b>Prepended text</b>. ");
});
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<button id="btn1">Prepend text</button>
</body>
</html>
After clicking
After clicking
jQuery after()
The jQuery after() method is used to insert specified content after the selected element. It
is just like jQuery append() method.
If you want to insert content before the selected element, you should use jQuery before()
method.
Syntax:
1. $(selector).after(content,function(index))
Function (index) It specifies a function that returns the content which is used to insert.
o index: It provides the index position of the element in the set.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").after("<p><b>Hello javatpoint.com</b></p>");
});
});
</script>
</head>
<body>
<button>Insert content after each p element</button>
<p>This is a tutorial website.</p>
<p>This is a training institute.</p>
</body>
</html>
After clicking
jQuery insertAfter()
The jQuery after() and jQuery insertAfter() both methods are used to perform the same
task of inserting additional contents after the selected elements.
In after() method, target is the selected element and content is placed as an argument of
the method.
1. $(target).after(contentToBeInserted)
1. $(contentToBeInserted).insertAfter(target)
Note: If you want to insert HTML elements before the selected element, you should use the
insertBefore() method.
Syntax:
1. $(content).insertAfter(selector)
Selector It is also a mandatory parameter. It specifies the place where you insert
the content.>
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("<span><b>Hello javatpoint.com</b></span>").insertAfter("p");
});
});
</script>
</head>
<body>
<button>Insert span element after each p element</button>
<p>This is a tutorial website.</p>
<p>This is a training institute.</p>
</body>
</html>
After clicking
jQuery append()
The jQuery append() method is used to insert specified content as the last child (at the
end of) the selected elements in the jQuery collection.
The append () and appendTo () methods are used to perform the same task. The only
difference between them is in the syntax.
Syntax:
1. $(selector).append(content, function(index, html))
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Newly added appended text</b>.");
});
$("#btn2").click(function(){
$("ol").append("<li><b>Newly added appended item</b></li>");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li>Item no.1</li>
<li>Item no.2</li>
<li>Item no.3</li>
</ol>
<button id="btn1">Append text</button>
<button id="btn2">Append item</button>
</body>
</html>
After clicking
jQuery appendTo()
The appendTo() method is used to add additional content at the end of the selected
elements. It is same as jQuery append() method. There is only syntactical difference
between append() and appendTo() methods.
Syntax:
1. $(content).appendTo(selector)
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("<span><b>Hello javatpoint.com</b></span>").appendTo("p");
});
});
</script>
</head>
<body>
<button>Add new content at the end of each p element</button>
<p>I am a new reader.</p>
<p>I am also a new reader.</p>
</body>
</html>
After clicking
jQuery clone()
The jQuery clone() method is used to make copies of the set of matched elements. It also
makes copies of their child nodes, texts and attributes. The clone() method is a convenient
way to duplicate elements on a page.
Syntax:
1. $(selector).clone(true|false)
1. <!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").clone().appendTo("body");
});
});
</script>
</head>
<body>
<p><b> javatpoint.com is a popular tutorial website.</b></p>
<p><b>javatpoint.com is a training institute also.</b></p>
<button>Click here, to clone all p elements, and append them to the body
element</button>
</body>
</html>
After clicking
jQuery remove()
The jQuery remove() method is used to remove the selected elements out of the DOM. It
removes the selected element itself, as well as everything inside it (including all texts and
child nodes). This method also removes the data and the events of the selected elements.
If you want to remove elements without removing data and events, you should use the detach()
method. If you want to remove only data and events, use the empty() method.
Syntax:
1. $(selector).remove(selector)
After clicking
After clicking
jQuery empty()
The jQuery empty() method is used to remove all child nodes and content from the selected
elements. This method doesn't remove the element itself.
If you want to remove the element without removing data and events, you should use the detach()
method.
If you want to remove the element as well as its data and events, you should use the remove()
method.
Syntax:
1. $(selector).empty()
Example of jQuery empty() method
Let's take an example to demonstrate the jQuery empty() method.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").empty();
});
});
</script>
</head>
<body>
<div style="height:150px;background-color:yellow">
Twinkle, twinkle, little star,<br/>
How I wonder what you are!</br>
Up above the world so high,<br/>
Like a diamond in the sky.<br/>
Twinkle, twinkle, little star,<br/>
How I wonder what you are!<br/>
<p><b>This poem is written inside the div.</b></p>
</div>
<p>This paragraph is written outside the div.</p>
<button>Execute empty() method to remove the content of div
element.</button>
</body>
</html>
After clicking
After clicking
jQuery detach()
The jQuery detach() method is used to remove the selected elements, including all texts
and child nodes and keeps only data and events.
This method saves a copy of the removed elements to reinsert them whenever they
needed later.
There are some other methods also which are used to remove elements e.g. jQuery
remove() method, jQuery empty() method etc. But there is a little difference among
them.
jQuery remove() method: This method is used to remove the elements as well as its
data and events.
jQuery empty() method: This method is used to remove only the content from the
selected elements.
Syntax:
1. $(selector).detach()
After clicking
After clicking
Difference between detach() and remove() method
Let's take an example to clear the difference between detach() and remove() method:
jQuery scrollTop()
The jQuery scrollTop method is used to set or return the vertical scrollbar position for the
selected element. When the scrollbar is on the top, it specifies the position 0.
o To return the position: When this method is used to return the position, it provides
the current vertical position of the first matched element in the set.
o To set the position: When this method is used to set the position, it sets the
vertical position of the scrollbar for all matched element.
Syntax:
1. $(selector).scrollTop()
After clicking
Another example of jQuery scrollTop()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>scrollTop demo</title>
<style>
div.demo {
background: #7fffd4 none repeat scroll 0 0;
border: 3px solid #666;
margin: 5px;
padding: 5px;
position: relative;
width: 200px;
height: 150px;
overflow: auto;
}
p{
margin: 10px;
padding: 5px;
border: 2px solid #666;
width: 1000px;
height: 1000px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="demo"><h1>Welcome to:</h1><p>javatpoint.com</p></div>
<script>
$( "div.demo" ).scrollTop( 300 );
</script>
</body>
</html>
jQuery attr()
The jQuery attr() method is used to set or return attributes and values of the selected
elements.
1. To return attribute value: This method returns the value of the first matched
element.
2. To set attribute value: This method is used to set one or more attribute/value
pairs of the set of matched elements.
Syntax:
To return an attribute's value:
1. $(selector).attr(attribute)
1. $(selector).attr(attribute,value)
1. $(selector).attr(attribute,function(index,currentvalue))
1. $(selector).attr({attribute:value, attribute:value,...})
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").attr("width", "500");
});
});
</script>
</head>
<body>
<img src="good-morning.jpg" alt="Good Morning Friends"width="284"
height="213"><br>
<button>Set the width attribute of the image</button>
</body>
</html>
After clicking
Benefits of using jQuery attr() method
It provides two main benefits:
o Convenience: When you use jQuery attr() method to get the value of the attribute
of an element then it can be call directly on a jQuery object and chained to other
jQuery methods.
o Cross-browser consistency: You can get rid from inconsistently changing of
attribute's value on different browsers or even on different versions of a single
browser.
jQuery prop()
jQuery prop() method is used for two purpose.
1. It is used to return the value of a property for the first element in a set of matched
elements.
2. It is used to set one or more property value for a set of matched element.
The jQuery prop() method is generally used to retrieve property values i.e. DOM properties
(like tagName, nodeName, defaultChecked) or own custom made properties. This is a very
convenient way to set the values of properties, especially the multiple properties.
If you want to retrieve HTML attributes, you should use the attr() method instead.
The removeProp() method is used to remove a property.
Syntax:
1. $(selector).prop(property)
1. $(selector).prop(property,value)
1. $(selector).prop(property,function(index,currentvalue))
1. $(selector).prop({property:value, property:value,...})
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var $x = $("div");
$x.prop("color","#e0eeee");
$x.append("The value of the color property: " + $x.prop("color"));
$x.removeProp("color");
$x.append("<br>Now the value of the color property: " + $x.prop("color"));
});
});
</script>
</head>
<body>
<button>Add and remove a property</button><br><br>
<div></div>
</body>
</html>
After clicking
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>prop demo</title>
<style>
p{
margin: 20px 0 0;
}
b{
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
<p></p>
<script>
$( "input" ).change(function() {
var $input = $( this );
$( "p" ).html(
".attr( \"checked\" ): <b>" + $input.attr( "checked" ) + "</b><br>" +
".prop( \"checked\" ): <b>" + $input.prop( "checked" ) + "</b><br>" +
".is( \":checked\" ): <b>" + $input.is( ":checked" ) ) + "</b>";
}).change();
</script>
</body>
</html>
After clicking
Difference between jQuery attr() and jQuery prop()
method:
This is a very common question because most of the people are confused about where to
use prop() method and where attr() method. The differences between them are very
important in specific situation.
1. The jQuery attr() method is used to retrieve the HTML attribute values while jQuery
prop() method is used to retrieve the property values.
2. The attr() method changes the attribute of the HTML tag while the prop() method
changes a property for the HTML tag as per the DOM tree.
3. Properties are generally simpler to deal with than attributes so the jQuery prop()
method is mostly used rather than attr() method.
jQuery offset()
The jQuery offset() method is used to get the current offset of the first matched element.
It provides two methods: to set or return the offset co-ordinates for the selected elements,
relative to the document.
o To return the offset: When this method is used to return the offset, it returns the
offset co-ordinates of the FIRST matched element. It specifies the object's two
properties: the top and left positions in pixels.
o To set the offset: When this method is used to set the offset, it sets the offset co-
ordinates of ALL matched elements.
Syntax:
1. $(selector).offset()
To SET the offset co-ordinates:
1. $(selector).offset({top:value,left:value})
1. $(selector).offset(function(index,currentoffset))
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var x = $("p").offset();
alert("Top: " + x.top + " Left: " + x.left);
});
});
</script>
</head>
<body>
<p>You are reading this tutorial on javatpoint.com</p>
<button>Click here to return the offset coordinates of the p element</button>
</body>
</html>
After clicking
After clicking
jQuery position()
The jQuery position () method makes you able to retrieve the current position of an element
relative to the parent element. It returns the position of the first matched element. This
method returns the object with two properties: top and left position in pixels.
The jQuery position() method is different from jQuery offset() method because the position() method
retrieves the current position of an element relative to the parent element while the offset() method
retrieves the current position relative to the document.
The position() method is more useful when you want to position a new element near another one
within the same containing DOM element.
Syntax:
1. $(selector).position()
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var x = $("p").position();
alert("Top position: " + x.top + " Left position: " + x.left);
});
});
</script>
</head>
<body>
<p>You are reading this tutorial on javatpoint.com</p>
<button>Click here to return the offset coordinates of the p element</button>
</body>
</html>
After clicking
After clicking
jQuery addClass()
The addclass() method is used to add one or more class name to the selected element. This
method is used only to add one or more class names to the class attributes not to remove
the existing class attributes.
If you want to add more than one class separate the class names with spaces.
Syntax:
1. $(selector).addClass(classname,function(index,oldclass))
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p:first").addClass("intro");
});
});
</script>
<style>
.intro {
font-size: 200%;
color: red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Add a class name to the first p element</button>
</body>
</html>
After clicking
jQuery hasClass()
The jQuery hasClass() method is used to check whether selected elements have specified
class name or not. It returns TRUE if the specified class is present in any of the selected
elements otherwise it returns FALSE.
Syntax:
1. $(selector).hasClass(classname)
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("p").hasClass("intro"));
});
});
</script>
<style>
.intro {
font-size: 150%;
color: Blue;
}
</style>
</head>
<body>
<h1>Look here, I am a heading.</h1>
<p class="intro">This is a paragraph.</p>
<p>This is also a paragraph.</p>
<button>Click here to check if any p element have an "intro" class?</button>
</body>
</html>
After clicking
jQuery hasClass() method example 2
Let's take another example to demonstrate jQuery hasClass() method.
<!DOCTYPE html>
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#result1").text( $("p#pid1").hasClass("red") );
$("#result2").text( $("p#pid2").hasClass("red") );
});
</script>
<style>
.red { color:red; }
.blue { color:blue; }
</style>
</head>
<body>
<p class="red" id="pid1">This is first paragraph.</p>
<p class="blue" id="pid2">This is second paragraph.</p>
<div id="result1"></div>
<div id="result2"></div>
</body>
</html>
true
true
ul li{
background-color:#7fffd4;
width:100px;
margin:5px;
padding:5px;
list-style-type:none;
width:200px;
}
</style>
</head>
<body>
<h1>jQuery .hasClass() function Example</h1>
<ul>
<li class="red">Red</li>
<li class="green">Green</li>
<li class="green red">Green Red</li>
<li class="blue">Blue</li>
</ul>
<input type="button" class="btn" value="Red Class" id="red">
<input type="button" class="btn" value="Green Class" id="green">
<input type="button" class="btn" value="Blue Class" id="blue">
<input type="button" class="btn" value="No Matching Class" id="noclass">
</body>
</html>
After clicking
jQuery toggleClass()
The jQuery toggleCLass() method is used to add or remove one or more classes from the
selected elements. This method toggles between adding and removing one or more class
name. It checks each element for the specified class names. If the class name is already
set, it removes and if the class name is missing, it adds.
In this way, it creates the toggle effect. It also facilitates you to specify to only add or only
remove by the use of switch parameter.
Syntax:
1. $(selector).toggleClass(classname,function(index,currentclass),switch)
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggleClass("main");
});
});
</script>
<style>
.main {
font-size: 150%;
color: red;
}
</style>
</head>
<body>
<button>Toggle class "main" for p elements</button>
<p>Hello! javatpoint.com</p>
<p>This is popular tutorial website.</p>
<p><b>Note:</b> Click repeatedly on the button to see the toggle effect.</p>
</body>
</html>
After clicking
www.javatpoint.com
Java Tutorial
SQL Tutorial
Android Tutorial
HTML Tutorial
etc.
jQuery width()
jQuery width() method is used to return or set the width of matched element.
To return width: When this method is used to return the width, it returns the width of first
matched element.
To set width:When this method is used to set the width, it sets the width for every
matched element.
o width()
o height()
o innerWidth()
o innerHeight()
o outerWidth()
o outerHeight()
Syntax:
1. $(selector).width()
1. $(selector).width(function(index,currentwidth))
To return width:
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Width of div: " + $("div").width());
});
});
</script>
</head>
<body>
<div style="height:100px;width:200px;padding:10px;margin:3px;border:1px solid
blue;background-color:lightpink;"></div><br>
<button>Execute the jQuery width() method to return width</button>
</body>
</html>
jQuery width() example 2
To set width:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>width demo</title>
<style>
div {
width: 100px;
height: 80px;
float: left;
margin: 5px;
background:orange;
cursor: pointer;
}
.mod {
background: green;
cursor: default;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<script>
var modWidth = 70;
$( "div" ).one( "click", function() {
$( this ).width( modWidth ).addClass( "mod" );
modWidth -= 10;
});
</script>
</body>
</html>
After clicking
jQuery height()
The jQuery height() method is used to return the current computed height for the first
element or set the height of every matched element. In other words, you can say that the
height() method is used for two purposes:
To return height: When this method is used to return height, it returns the height of first
matched element.
To set height: When this method is used to set height, it sets height of all matched
elements.
The before() and insertBefore() both methods are used to perform same task. The main difference
between them is in syntax, and the placement of the content and the target.
Syntax:
1. $(selector).height()
1. $(selector).height(function(index,currentheight))
To return Height:
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Height of div: " + $("div").height());
});
});
</script>
</head>
<body>
<div style="height:100px;width:200px;padding:10px;margin:3px;border:1px solid
blue;background-color:lightpink;"><div class="div">Hello Guys!<br/> This is
javatpoint.com</div></div><br>
<button>Display the height of div</button>
</body>
</html>
After clicking
jQuery height() example 2
To set height:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>height demo</title>
<style>
div {
width: 50px;
height: 100px;
float: left;
margin: 5px;
background: rgb(255,140,0);
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
$( "div" ).one( "click", function() {
$( this ).height( 50 ).css({
cursor: "auto",
backgroundColor: "green"
});
});
</script>
</body>
</html>
After clicking
jQuery innerWidth()
jQuery innerWidth() method is used to return the inner width of the first matched
This image explains that jQuery innerWidth () method includes padding but not border and
margin.
Syntax:
1. $(selector).innerWidth()
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Inner width of div is: " + $("div").innerWidth());
});
});
</script>
</head>
<body>
<div style="height:100px;width:500px;padding:10px;margin:3px;border:1px solid
blue;background-color:lightpink;"></div><br>
<button>Click here to get the inner width of the div</button>
</body>
</html>
After clicking
jQuery innerWidth() example 2
Let's take an example to demonstrate the effect of jQuery innerWidth() method.
<!DOCTYPE html>
<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>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var color = $(this).css("background-color");
var width = $(this).innerWidth();
$("#result").html("Inner Width is <span>" + width + "</span>.");
$("#result").css({'color': color, 'background-color':'white'});
});
});
</script>
<style>
#div1{ margin:10px;padding:10px; border:2px solid #666; width:60px;}
#div2 { margin:15px;padding:15px; border:4px solid #666; width:60px;}
#div3 { margin:20px;padding:20px; border:6px solid #666; width:60px;}
#div4 { margin:25px;padding:25px; border:8px solid #666; width:60px;}
</style>
</head>
<body>
<p>Click on any square:</p>
<span id="result"> </span>
<div id="div1" style="background-color:orange;"></div>
<div id="div2" style="background-color:green;"></div>
<div id="div3" style="background-color:brown;"></div>
<div id="div4" style="background-color:violet;"></div>
</body>
</html>
After clicking
jQuery innerHeight()
The jQuery innerHeight () method is used to return the inner height of first matched
element. It includes padding but not border and margin.
In the above image, you can see that innerHeight () method includes padding but not
border and margin.
Syntax:
1. $(selector).innerHeight()
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Inner height of the div is: " + $("div").innerHeight());
});
});
</script>
</head>
<body>
<div style="height:100px;width:500px;padding:10px;margin:3px;border:1px solid
blue;background-color:lightpink;"></div><br>
<button>Click here to get the inner height of the div</button>
</body>
</html>
After clicking
jQuery innerHeight() example 2
Let's take an example to demonstrate how to change the inner height of each div.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>innerHeight demo</title>
<style>
div {
width: 60px;
padding: 10px;
height: 100px;
float: left;
margin: 5px;
background: orange;
cursor: pointer;
}
.mod {
background: green;
cursor: default;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<script>
var modHeight = 80;
$( "div" ).one( "click", function() {
$( this ).innerHeight( modHeight ).addClass( "mod" );
modHeight -= 8;
});
</script>
</body>
</html>
After clicking
jQuery outerWidth()
jQuery outerWidth() method is used to return the outer width of the first matched
The jQuery outerWidth () method works for both visible and hidden elements.
In the above image, you can see that jQuery outerWidth() method includes border and
padding both.
Syntax:
1. $(selector).outerWidth(includeMargin)
Parameters of jQuery outerWidth() method
Parameter Description
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Outer width of div is: " + $("div").outerWidth());
});
});
</script>
</head>
<body>
<div style="height:100px;width:500px;padding:10px;margin:3px;border:1px solid
blue;background-color:lightpink;"></div><br>
<button>Click here to get the outer width of the div</button>
</body>
</html>
After clicking
In the above example, you can see that border and padding both are included in the
outerHeight() method.
Syntax:
1. $(selector).outerHeight(includeMargin)
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Outer height of the div is: " + $("div").outerHeight());
});
});
</script>
</head>
<body>
<div style="height:100px;width:500px;padding:10px;margin:3px;border:1px solid
blue;background-color:lightpink;"></div><br>
<button>Click here to get the outer height of the div</button>
</body>
</html>
jQuery outerHeight() example 2
Let's take an example to demonstrate how to change the inner height of each div.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>outerHeight demo</title>
<style>
div {
width: 60px;
padding: 10px;
height: 100px;
float: left;
margin: 5px;
background: Orange;
cursor: pointer;
}
.mod {
background: green;
cursor: default;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<script>
var modHeight = 80;
$( "div" ).one( "click", function() {
$( this ).outerHeight( modHeight ).addClass( "mod" );
modHeight -= 8;
});
</script>
</body>
</html>
After clicking
jQuery wrap()
jQuery wrap() method is used to wrap specified HTML elements around each selected
element. The wrap () function can accept any string or object that could be passed through
the $() factory function.
Syntax:
1. $(selector).wrap(wrappingElement,function(index))
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").wrap("<div></div>");
});
});
</script>
<style>
div{background-color: pink;}
</style>
</head>
<body>
<p>Hello Guys!</p>
<p>This is javatpoint.com</p>
<button>Wrap a div element around each p element</button>
</body>
</html>
jQuery serialize()
jQuery serialize() method is used to create a text string in standard URL-encoded notation.
It is used in form controls like <input>, <textarea>, <select> etc. It serializes the form
values so that its serialized values can be used in the URL query string while making an
AJAX request.
Syntax:
1. $ (selector).serialize()
jQuery serialize() example
Let's take an example which serializes a form values.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").text($("form").serialize());
});
});
</script>
</head>
<body>
<form action="">
First name: <input type="text" name="FirstName" value="Sonoo"><br>
Last name: <input type="text" name="LastName" value="Jaiswal"><br>
</form>
<button>Serialize form values</button>
<div></div>
</body>
</html>
After clicking
jQuery serializeArray()
The jQuery serializedArray() Method is used to create a JavaScript array of objects by
serializing form values. It operates on a jQuery collection of forms and form controls. You
can select one or more form elements such as <input>, <textarea> or the form element
itself.
Syntax:
1. $(selector).serializeArray()
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var x = $("form").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " ");
});
});
});
</script>
</head>
<body>
<form action="">
First name: <input type="text" name="FirstName" value="Ajeet"><br>
Last name: <input type="text" name="LastName" value="Maurya"><br>
</form>
<button>Serialize form values</button>
<div id="results"></div>
</body>
</html>
After clicking
jQuery Events
jQuery events are the actions that can be detected by your web application. They are used
to create dynamic web pages. An event shows the exact moment when something happens.
o A mouse click
o An HTML form submission
o A web page loading
o A keystroke on the keyboard
o Scrolling of the web page etc.
Mouse Events
o click
o dblclick
o mouseenter
o mouseleave
Keyboard Events
o keyup
o keydown
o keypress
Form Events
o submit
o change
o blur
o focus
Document/Window Events
o load
o unload
o scroll
o resize
Note: A term "fires" is generally used with events. For example: The click event fires in the moment
you press a key.
1. $("p").click ();
The next step defines what should happen when the event fires. You must pass a function to
the event.
1. $("p").click(function(){
2. // action goes here!!
3. });
jQuery click()
When you click on an element, the click event occurs and once the click event occurs it
execute the click () method or attaches a function to run.
It is generally used together with other events of jQuery.
Syntax:
1. $(selector).click()
1. $(selector).click(function)
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
alert("This paragraph was clicked.");
});
});
</script>
</head>
<body>
<p>Click on the statement.</p>
</body>
</html>
After clicking
Let's take an example to demonstrate the jquery click() event. In
this example, when you click on the heading element, it will hide
the current heading. <!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.
min.js"></script>
<script>
$(document).ready(function(){
$("h1,h2,h3").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<h1>This heading will disappear if you click on this.</h1>
<h2>I will also disappear.</h2>
<h3>Me too.</h3>
</body>
</html>
This heading will disappear if you click on this.
I will also disappear.
Me too.
After clicking
I will also disappear.
Me too.
jQuery bind()
The jQuery bind() event is used to attach one or more event handlers for selected elements
from a set of elements. It specifies a function to run when the event occurs.
Syntax:
1. $(selector).bind(event,data,function,map)
Function It is a mandatory parameter. It executes the function to run when the event
occurs.
Map It specifies an event map which contains one or more events or functions
attached to the element.
After clicking
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>bind demo</title>
<style>
p{
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click or double click on the statement.</p>
<span></span>
<script>
$( "p" ).bind( "click", function( event ) {
var str = "( " + event.pageX + ", " + event.pageY + " )";
$( "span" ).text( "This is a single click! " + str );
});
$( "p" ).bind( "dblclick", function() {
$( "span" ).text( "This is a double click on " + this.nodeName );
});
$( "p" ).bind( "mouseenter mouseleave", function( event ) {
$( this ).toggleClass( "over" );
});
</script>
</body>
</html>
After clicking
jQuery blur()
The jQuery blur event occurs when element loses focus. It can be generated by via
keyboard commands like tab key or mouse click anywhere on the page.
It makes you enable to attach a function to the event that will be executed when the
element loses focus. Originally, this event was used only with form elements like <input>.
In latest browsers, it has been extended to include all element types.
Syntax:
1. $(selector).blur()
1. $(selector).blur(function)
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("input").blur(function(){
alert("This text box has lost its focus.");
});
});
</script>
</head>
<body>
Enter your name: <input type="text">
</body>
</html>
This event is implicitly used to limited sets of elements such as form elements like <input>,
<select> etc. and links <a href>. The focused elements are usually highlighted in some way
by the browsers.
Syntax:
1. $(selector).focus()
1. $(selector).focus(function)
Function It is an optional parameter. It is used to specify the function to run when the
element gets the focus.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>focus demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><input type="text" value="you can't write"></p>
<p><input type="password"> </p>
<script>
$( "input[type=text]" ).focus(function() {
$( this ).blur();
});
</script>
</body>
</html>
jQuery select()
jQuery select()
jQuery select event occurs when a text is marked or selected in text area or a text field. This event is limi
type="text"> fields and <textarea> boxes. When the select event occurs, the select() method attaches a
Syntax:
1. $(selector).select()
1. $(selector).select(function)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>select demo</title>
<style>
p {
color: red;
}
div {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Select the text on the box: click and drag the mouse to select text.</p>
<input type="text" value="javatpoint.com">
<input type="text" value="sssit.org">
<div></div>
<script>
$( ":input" ).select(function() {
$( "div" ).text( "Some text was selected" ).show().fadeOut( 2000 );
});
</script>
</body>
</html>
After selection
jQuery change()
jQuery change event occurs when the value of an element is changed. It works only on form
fields. When the change event occurs, the change () method attaches a function with it to
run.
Note: This event is limited to <input> elements, <textarea> boxes and <select> elements.
o For select boxes, checkboxes, and radio buttons: The event is fired immediately
when the user makes a selection with the mouse.
o For the other element types: The event is occurred when the field loses focus.
Syntax:
1. $(selector).change()
1. $(selector).change(function)
Function It is an optional parameter. It is used to specify the function to run when the
change event occurs for the selected elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>change demo</title>
<style>
div {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<select id="se" name="actors" >
<option>Uthappa</option>
<option selected="selected">Kattapa</option>
<option>Veerappa</option>
<option>Bahubali</option>
<option>Bhallal Dev</option>
<option>Awantika</option>
</select>
<div id="loc"></div>
<script>
$( "select" ) .change(function () {
document.getElementById("loc").innerHTML="You selected:
"+document.getElementById("se").value;
});
</script>
</body>
</html>
After clicking
Let's see another example of jQuery change event where we are providing option to select
multiple data using ctrl key.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>change demo</title>
<style>
div {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<select name="Employees" multiple="multiple">
<option>Uthappa</option>
<option selected="selected">Kattapa</option>
<option>Veerappa</option>
<option selected="selected">Bahubali</option>
<option>Bhallal Dev</option>
<option>Awantika</option>
</select>
<div></div>
<script>
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$( "div" ).text( str );
})
.change();
</script>
</body>
</html>
After selection
jQuery submit()
jQuery submit event is sent to the element when the user attempts to submit a form.
This event is only attached to the <form> element. Forms can be submitted either by
clicking on the submit button or by pressing the enter button on the keyboard when that
certain form elements have focus. When the submit event occurs, the submit() method
attaches a function with it to run.
Syntax:
1. $(selector).submit()
1. $(selector).submit(function)
Function It is an optional parameter. It is used to specify the function to run when the
submit event is executed.
jQuery keydown()
When you press a key on the keyboard, the keydown() event is occurred and once the
keydown() event is occurred, it executes the function associated with keydown() method to
run.
Syntax:
1. $(selector).keydown()
1. $(selector).keydown(function)
jQuery keypress()
The jQuery keypress () event is occurred when a keyboard button is pressed down. This
event is similar to keydown() event. The keypress() method is executed or attach a function
to run when a keypress() event occurs.
Syntax:
1. $(selector).keypress()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
i = 0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text (i += 1);
});
});
</script>
</head>
<body>
Write something: <input type="text">
<p>Keypresses: <span>0</span></p>
</body>
</html>
After writing
jQuery keyup()
The jQuery keyup() event occurs when a keyboard button is released after pressing. This
method is executed or attach a function to run when a keyup() event occurs.
Syntax:
1. $(selector).keyup()
1. $(selector).keyup(function)
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("input").keydown(function(){
$("input").css("background-color", "red");
});
$("input").keyup(function(){
$("input").css("background-color", "yellow");
});
});
</script>
</head>
<body>
Write something: <input type="text">
</body>
</html>
jQuery mouseenter()
The mouseenter() method adds an event handler function to an HTML element. This
function is executed, when the mouse pointer enters the HTML element.
When you enter your mouse cursor over the selected element, it triggers the mouseenter
event and once the mouseenter event is occurred, it executes the mouseenter() method to
attach the event handler function to run.
Syntax:
1. $(selector).mouseenter()
1. $(selector).mouseenter(function)
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").mouseenter(function(){
$("p").css("background-color", "lightgreen");
});
$("p").mouseleave(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<p>Move your mouse cursor over this statement.</p>
</body>
</html>
jQuery mouseleave()
The mouseleave() method adds an event handler function to an HTML element. This
function is executed, when the mouse pointer leaves the HTML element.
When your mouse cursor leaves the selected element, it triggers the mouseleave event and
once the mouseleave event is occurred, it executes the mouseleave() method attached with
the event handler function to run.
Syntax:
1. $(selector).mouseleave()
1. $(selector).mouseleave(function)
After leaving