2.
jQuery Fundamentals
jQuery:
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a
nice motto: Write less, do more.
jQuery simplifies HTML document traversing, event handling, animating, and Ajax
interactions for rapid web development. jQuery is a JavaScript toolkit designed to simplify
various tasks by writing less code.
Advantages of jQuery:
• DOM manipulation − The jQuery made it easy to select DOM elements, negotiate
them and modifying their content by using cross-browser open source selector
engine called Sizzle.
• Event handling − The jQuery offers an elegant way to capture a wide variety of
events, such as a user clicking on a link, without the need to clutter the HTML code
itself with event handlers.
• AJAX Support − The jQuery helps you a lot to develop a responsive and featurerich
site using AJAX technology.
• Animations − The jQuery comes with plenty of built-in animation effects which you
can use in your websites.
• Lightweight − The jQuery is very lightweight library - about 19KB in size (Minified and
gzipped).
• Cross Browser Support − The jQuery has cross-browser support, and works well in IE
6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
• Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax.
There are two ways to use jQuery.
• Local Installation − You can download jQuery library on your local machine and
include it in your HTML code.
• CDN Based Version − You can include jQuery library into your HTML code directly
from Content Delivery Network (CDN).
1 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
Local installation:
• Go to the https://jquery.com/download/ to download the latest version available.
• Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g.
/jquery.
Example:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript" src =
"/jquery/jquery-2.1.3.min.js">
</script>
<script type = "text/javascript">
$(document).ready(function() {
document.write("Hello, World!");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
CDN Based Version:
You can include jQuery library into your HTML code directly from Content Delivery
Network (CDN). Google and Microsoft provides content deliver for the latest version.
Example:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src =
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.m
in.js">
</script>
<script type = "text/javascript">
$(document).ready(function() {
document.write("Hello, World!");
});
2 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
jQuery Selectors:
A jQuery Selector is a function which makes use of expressions to find out matching
elements from a DOM based on the given criteria.
Simply you can say, selectors are used to select one or more HTML elements using jQuery.
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 factory function $()
makes use of following three building blocks while selecting elements in a given document
−
Sr.No. Selector & Description
1 Tag Name
Represents a tag name available in the DOM. For
example $('p') selects all paragraphs <p> in the document.
2 Tag ID
Represents a tag available with the given ID in the DOM. For
example $('#some-id') selects the single element in the document
that has an ID of some-id.
3 Tag Class
Represents a tag available with the given class in the DOM. For
example $('.some-class') selects all elements in the document that
have a class of some-class.
3 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
All the above items can be used either on their own or in combination with other selectors.
All the jQuery selectors are based on the same principle except some tweaking.
Example
Following is a simple example which makes use of Tag Selector. This would select all the
elements with a tag name p.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src =
"https://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", "yellow");
});
</script>
</head>
<body>
<div>
<p class = "myclass">This is a paragraph.</p>
<p id = "myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>
</body>
</html>
How to Use Selectors?
The selectors are very useful and would be required at every step while using jQuery. They
get the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.
4 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
Sr.No. Selector & Description
1 Name
Selects all elements which match with the given element Name.
2 #ID
Selects a single element which matches with the given ID.
3 .Class
Selects all elements which match with the given Class.
4 Universal (*)
Selects all elements available in a DOM.
5 Multiple Elements E, F, G
Selects the combined results of all the specified selectors E, F or G.
jQuery Events
Events are actions that can be detected by your Web Application.
Following are the examples events −
• A mouse click
• A web page loading
• Taking mouse over an element
• Submitting an HTML form
• A keystroke on your keyboard, etc.
When these events are triggered, you can then use a custom function to do pretty much
whatever you want with the event. These custom functions call Event Handlers.
5 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
Here are some common DOM events:
Mouse Keyboard Events Form Events Document/Window
Events Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload
jQuery Syntax For Event Methods
In jQuery, most DOM events have an equivalent jQuery method. To assign a click
event to all paragraphs on a page, you can do this:
$("p").click();
The next step is to define what should happen when the event fires. You must pass a
function to the event:
$("p").click(function(){
// action goes here!!
});
jQuery Event Methods:
click()
The click() method attaches an event handler function to an HTML element.
The function is executed when the user clicks on the HTML element.
6 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
The following example says: When a click event fires on a <p> element; hide the
current <p> element:
Example
$("p").click(function(){
$(this).hide();
});
dblclick()
The dblclick() method attaches an event handler function to an HTML element.
The function is executed when the user double-clicks on the HTML element:
Example
$("p").dblclick(function(){
$(this).hide();
});
mouseenter()
The mouseenter() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer enters the HTML element:
Example
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
mouseleave()
The mouseleave() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer leaves the HTML element:
Example
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
mousedown()
The mousedown() method attaches an event handler function to an HTML element.
7 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
The function is executed, when the left, middle or right mouse button is pressed down,
while the mouse is over the HTML element:
Example
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
mouseup()
The mouseup() method attaches an event handler function to an HTML element.
The function is executed, when the left, middle or right mouse button is released, while the
mouse is over the HTML element:
Example
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});
hover()
The hover() method takes two functions and is a combination of
the mouseenter() and mouseleave() methods.
The first function is executed when the mouse enters the HTML element, and the second
function is executed when the mouse leaves the HTML element:
Example
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
focus()
The focus() method attaches an event handler function to an HTML form field.
The function is executed when the form field gets focus:
Example
8 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
blur()
The blur() method attaches an event handler function to an HTML form field.
The function is executed when the form field loses focus:
Example
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
The on() Method
The on() method attaches one or more event handlers for the selected elements.
Attach a click event to a <p> element:
Example
$("p").on("click", function(){
$(this).hide();
});
jQuery Effects
jQuery hide() and show()
With jQuery, you can hide and show HTML elements with the hide() and show() methods:
Example
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
Syntax:
9 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
$(selector).hide(speed,callback);
$(selector).show(speed,callback);
The optional speed parameter specifies the speed of the hiding/showing, and can take the
following values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after
the hide() or show() method completes (you will learn more about callback functions in a
later chapter).
The following example demonstrates the speed parameter with hide():
Example
$("button").click(function(){
$("p").hide(1000);
});
jQuery toggle()
You can also toggle between hiding and showing an element with the toggle() method.
Shown elements are hidden and hidden elements are shown:
Example
$("button").click(function(){
$("p").toggle();
});
Syntax:
$(selector).toggle(speed,callback);
The optional speed parameter can take the following values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after toggle() completes.
jQuery Fading Methods
With jQuery you can fade an element in and out of visibility.
jQuery has the following fade methods:
• fadeIn()
10 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
• fadeOut()
• fadeToggle()
• fadeTo()
jQuery fadeIn() Method
The jQuery fadeIn() method is used to fade in a hidden element.
Syntax:
$(selector).fadeIn(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
The following example demonstrates the fadeIn() method with different parameters:
Example
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
jQuery fadeOut() Method
The jQuery fadeOut() method is used to fade out a visible element.
Syntax:
$(selector).fadeOut(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
The following example demonstrates the fadeOut() method with different parameters:
Example
11 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
jQuery fadeToggle() Method
The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.
If the elements are faded out, fadeToggle() will fade them in.
If the elements are faded in, fadeToggle() will fade them out.
Syntax:
$(selector).fadeToggle(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
The following example demonstrates the fadeToggle() method with different parameters:
Example
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
jQuery fadeTo() Method
The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).
Syntax:
$(selector).fadeTo(speed,opacity,callback);
The required speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
The required opacity parameter in the fadeTo() method specifies fading to a given opacity
(value between 0 and 1).
The optional callback parameter is a function to be executed after the function completes.
12 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
The following example demonstrates the fadeTo() method with different parameters:
Example
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
jQuery Sliding Methods
With jQuery you can create a sliding effect on elements.
jQuery has the following slide methods:
• slideDown()
• slideUp()
• slideToggle()
jQuery slideDown() Method
The jQuery slideDown() method is used to slide down an element.
Syntax:
$(selector).slideDown(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the sliding completes.
The following example demonstrates the slideDown() method:
Example
$("#flip").click(function(){
$("#panel").slideDown();
});
jQuery slideUp() Method
The jQuery slideUp() method is used to slide up an element.
Syntax:
13 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
$(selector).slideUp(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the sliding completes.
The following example demonstrates the slideUp() method:
Example
$("#flip").click(function(){
$("#panel").slideUp();
});
jQuery slideToggle() Method
The jQuery slideToggle() method toggles between the slideDown() and slideUp() methods.
If the elements have been slid down, slideToggle() will slide them up.
If the elements have been slid up, slideToggle() will slide them down.
$(selector).slideToggle(speed,callback);
The optional speed parameter can take the following values: "slow", "fast", milliseconds.
The optional callback parameter is a function to be executed after the sliding completes.
The following example demonstrates the slideToggle() method:
Example
$("#flip").click(function(){
$("#panel").slideToggle();
});
jQuery Animations - The animate() Method
The jQuery animate() method is used to create custom animations.
Syntax:
$(selector).animate({params},speed,callback);
The required params parameter defines the CSS properties to be animated.
The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
14 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
The optional callback parameter is a function to be executed after the animation completes.
The following example demonstrates a simple use of the animate() method; it moves a
<div> element to the right, until it has reached a left property of 250px:
Example
$("button").click(function(){
$("div").animate({left: '250px'});
});
Multiple properties can be animated at the same time:
Example
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
jQuery stop() Method
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:
15 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
Example
$("#stop").click(function(){
$("#panel").stop();
});
jQuery Method Chaining
Until now we have been writing jQuery statements one at a time (one after the other).
However, there is a technique called chaining, that allows us to run multiple jQuery
commands, one after the other, on the same element(s).
Tip: This way, browsers do not have to find the same element(s) more than once.
To chain an action, you simply append the action to the previous action.
The following example chains together the css(), slideUp(), and slideDown() methods. The
"p1" element first changes to red, then it slides up, and then it slides down:
Example
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
jQuery Callback Functions
JavaScript statements are executed line by line. However, with effects, the next line of code
can be run even though the effect is not finished. This can create errors.
To prevent this, you can create a callback function.
A callback function is executed after the current effect is finished.
Typical syntax: $(selector).hide(speed,callback);
Examples
The example below has a callback parameter that is a function that will be executed after
the hide effect is completed:
Example with Callback
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
16 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
jQuery Manipulation methods
Get/Set methods
Get Methods:
• text() - Sets or returns the text content of selected elements
• html() - Sets or returns the content of selected elements (including HTML markup)
• val() - Sets or returns the value of form fields
Example
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
Get Attributes - attr()
The jQuery attr() method is used to get attribute values.
The following example demonstrates how to get the value of the href attribute in a link:
Example
$("button").click(function(){
alert($("#w3s").attr("href"));
});
Set Methods:
• text() - Sets or returns the text content of selected elements
• html() - Sets or returns the content of selected elements (including HTML markup)
• val() - Sets or returns the value of form fields
Example
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
17 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
Set Attributes - attr()
The jQuery attr() method is also used to set/change attribute values.
The following example demonstrates how to change (set) the value of the href attribute in a
link:
Example
$("button").click(function(){
$("#w3s").attr("href", "https://www.w3schools.com/jquery/");
});
Insert Methods:
• append() - Inserts content at the end of the selected elements
• prepend() - Inserts content at the beginning of the selected elements
• after() - Inserts content after the selected elements
• before() - Inserts content before the selected element
The jQuery append() method inserts content AT THE END of the selected HTML elements.
Example
$("p").append("Some appended text.");
The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML
elements.
Example
$("p").prepend("Some prepended text.");
The jQuery after() method inserts content AFTER the selected HTML elements.
The jQuery before() method inserts content BEFORE the selected HTML elements.
Example
18 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
$("img").after("Some text after");
$("img").before("Some text before");
jQuery Remove Elements
To remove elements and content, there are mainly two jQuery methods:
• remove() - Removes the selected element (and its child elements)
• empty() - Removes the child elements from the selected element
The jQuery remove() method removes the selected element(s) and its child elements.
Example
$("#div1").remove();
The jQuery empty() method removes the child elements of the selected element(s).
Example
$("#div1").empty();
The jQuery remove() method also accepts one parameter, which allows you to filter the
elements to be removed.
The parameter can be any of the jQuery selector syntaxes.
The following example removes all <p> elements with class="test":
Example
$("p").remove(".test");
This example removes all <p> elements with class="test" and class="demo":
Example
$("p").remove(".test, .demo");
jQuery css() Method
The css() method sets or returns one or more style properties for the selected elements.
Return a CSS Property
To return the value of a specified CSS property, use the following syntax:
19 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat
css("propertyname");
The following example will return the background-color value of the FIRST matched
element:
Example
$("p").css("background-color");
Set a CSS Property
To set a specified CSS property, use the following syntax:
css("propertyname","value");
The following example will set the background-color value for ALL matched elements:
Example
$("p").css("background-color", "yellow");
Set Multiple CSS Properties
To set multiple CSS properties, use the following syntax:
css({"propertyname":"value","propertyname":"value",...});
The following example will set a background-color and a font-size for ALL matched
elements:
Example
$("p").css({"background-color": "yellow", "font-size": "200%"});
20 Prepared By:
Prof. Chirag Prajapati – SDJ International College, Vesu, Surat