What is jQuery?
jQuery is a library of JavaScript Functions.
jQuery is a lightweight "write less, do more" JavaScript library.
The jQuery library contains the following features:
HTML element selections
HTML element manipulation
CSS manipulation
HTML event functions
JavaScript Effects and animations
HTML DOM traversal and modification
AJAX
Utilities
jQuery Syntax
With jQuery you select (query) HTML elements and perform "actions" on them.
jQuery Syntax Examples
$(this).hide()
Demonstrates the jQuery hide() method, hiding the current HTML element.
$("#test").hide()
Demonstrates the jQuery hide() method, hiding the element with id="test".
$("p").hide()
Demonstrates the jQuery hide() method, hiding all <p> elements.
$(".test").hide()
Demonstrates the jQuery hide() method, hiding all elements with class="test".
jQuery Syntax
The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s).
Basic syntax is: $(selector).action()
A dollar sign to define jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides current element
$("p").hide() - hides all paragraphs
$("p.test").hide() - hides all paragraphs with class="test"
$("#test").hide() - hides the element with id="test"
jQuery uses a combination of XPath and CSS selector syntax.
You will learn more about the selector syntax in the next chapter of this tutorial.
The Document Ready Function
You might have noticed that all jQuery methods, in our examples, are inside a document.ready() function:
$(document).ready(function(){
// jQuery functions go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
Here are some examples of actions that can fail if functions are run before the document is fully loaded:
Trying to hide an element that doesn't exist
Trying to get the size of an image that is not loaded
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML elements as a group or as a single element.
jQuery AJAX
jQuery Examples
jQuery Quiz
jQuery Quiz
jQuery Reference
jQuery Selectors
jQuery Events
jQuery Effects
jQuery HTML
jQuery CSS
jQuery AJAX
jQuery Misc
jQuery Selectors
« Previous
Next Chapter »
jQuery selectors allow you to select and manipulate HTML elements as a group or as a single element.
jQuery Selectors
In the previous chapter we looked at some examples of how to select different HTML elements.
It is a key point to learn how jQuery selects exactly the elements you want to apply an effect to.
jQuery selectors allow you to select HTML elements (or groups of elements) by element name, attribute name or by content.
In HTML DOM terms:
Selectors allow you to manipulate DOM elements as a group or as a single node.
jQuery Element Selectors
jQuery uses CSS selectors to select HTML elements.
$("p") selects all <p> elements.
$("p.intro") selects all <p> elements with class="intro".
$("p#demo") selects all <p> elements with id="demo".
jQuery Attribute Selectors
jQuery uses XPath expressions to select elements with given attributes.
$("[href]") select all elements with an href attribute.
$("[href='#']") select all elements with an href value equal to "#".
$("[href!='#']") select all elements with an href attribute NOT equal to "#".
$("[href$='.jpg']") select all elements with an href attribute that ends with ".jpg".
jQuery CSS Selectors
jQuery CSS selectors can be used to change CSS properties for HTML elements.
The following example changes the background-color of all p elements to yellow:
Example
$("p").css("background-color","yellow");
Try it yourself »
Some More Examples
Syntax
Description
$(this)
Current HTML element
$("p")
All <p> elements
$("p.intro")
All <p> elements with class="intro"
$("p#intro")
All <p> elements with id="intro"
$("p#intro:first")
The first <p> element with id="intro"
$(".intro")
All elements with class="intro"
$("#intro")
The first element with id="intro"
$("ul li:first")
The first <li> element of each <ul>
$("[href$='.jpg']")
All elements with an href attribute that ends with ".jpg"
$("div#intro .head")
All elements with class="head" inside a <div> element with id="intro"
Use our excellent jQuery Selector Tester to experiment with the different selectors.
For a full reference please go to our jQuery Selectors Reference
jQuery Events
jQuery is tailor made to handle events.
jQuery Event Functions
The jQuery event handling methods are core functions in jQuery.
Event handlers are method that are called when "something happens" in HTML. The term "triggered (or "fired") by an event" is often used.
It is common to put jQuery code into event handler methods in the <head> section:
Example
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
Try it yourself »
In the example above, a function is called when the click event for the button is triggered:
$("button").click(function() {..some code... } )
The method hides all <p> elements:
$("p").hide();
Functions In a Separate File
If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, put your jQuery functions in a separate .js file.
When we demonstrate jQuery here, the functions are added directly into the <head> section, However, sometimes it is preferable to place them in a separate file, like this (refer to the file with the src attribute):
Example
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="my_jquery_functions.js"></script>
</head>
jQuery Name Conflicts
jQuery uses the $ sign as a shortcut for jQuery.
Some other JavaScript libraries also use the dollar sign for their functions.
The jQuery noConflict() method specifies a custom name (like jq), instead of using the dollar sign.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var jq=jQuery.noConflict();
jq(document).ready(function(){
jq("button").click(function(){
jq("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
jQuery Events
Here are some examples of event methods in jQuery:
Event Method
Description
$(document).ready(function)
Binds a function to the ready event of a document
(when the document is finished loading)
$(selector).click(function)
Triggers, or binds a function to the click event of selected elements
$(selector).dblclick(function)
Triggers, or binds a function to the double click event of selected elements
$(selector).focus(function)
Triggers, or binds a function to the focus event of selected elements
$(selector).mouseover(function)
Triggers, or binds a function to the mouseover event of selected elements
For a full jQuery event reference, please go to our jQuery Events Reference.
jQuery Effects
Hide, Show, Toggle, Slide, Fade, and Animate. WOW!
Examples
jQuery hide()
Demonstrates a simple jQuery hide() method.
jQuery hide()
Another hide() demonstration. How to hide parts of text.
jQuery slideToggle()
Demonstrates a simple slide panel effect.
jQuery fadeTo()
Demonstrates a simple jQuery fadeTo() method.
jQuery animate()
Demonstrates a simple jQuery animate() method.
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();
});
Try it yourself »
Both hide() and show() can take the two optional parameters: speed and callback.
Syntax:
$(selector).hide(speed,callback)
$(selector).show(speed,callback)
The speed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", "normal", or milliseconds:
Example
$("button").click(function(){
$("p").hide(1000);
});
Try it yourself »
The callback parameter is the name of a function to be executed after the hide (or show) function completes. You will learn more about the callback parameter in the next chapter of this tutorial.
jQuery Toggle
The jQuery toggle() method toggles the visibility of HTML elements using the show() or hide() methods.
Shown elements are hidden and hidden elements are shown.
Syntax:
$(selector).toggle(speed,callback)
The speed parameter can take the following values: "slow", "fast", "normal", or milliseconds.
Example
$("button").click(function(){
$("p").toggle();
});
Try it yourself »
The callback parameter is the name of a function to be executed after the hide (or show) method completes.
jQuery Slide - slideDown, slideUp, slideToggle
The jQuery slide methods gradually change the height for selected elements.
jQuery has the following slide methods:
$(selector).slideDown(speed,callback)
$(selector).slideUp(speed,callback)
$(selector).slideToggle(speed,callback)
The speed parameter can take the following values: "slow", "fast", "normal", or milliseconds.
The callback parameter is the name of a function to be executed after the function completes.
slideDown() Example
$(".flip").click(function(){
$(".panel").slideDown();
});
Try it yourself »
slideUp() Example
$(".flip").click(function(){
$(".panel").slideUp()
})
Try it yourself »
slideToggle() Example
$(".flip").click(function(){
$(".panel").slideToggle();
});
Try it yourself »
jQuery Fade - fadeIn, fadeOut, fadeTo
The jQuery fade methods gradually change the opacity for selected elements.
jQuery has the following fade methods:
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
The speed parameter can take the following values: "slow", "fast", "normal", or milliseconds.
The opacity parameter in the fadeTo() method allows fading to a given opacity.
The callback parameter is the name of a function to be executed after the function completes.
fadeTo() Example
$("button").click(function(){
$("div").fadeTo("slow",0.25);
});
Try it yourself »
fadeOut() Example
$("button").click(function(){
$("div").fadeOut(4000);
});
Try it yourself »
jQuery Custom Animations
The syntax of jQuery's method for making custom animations is:
$(selector).animate({params},[duration],[easing],[callback])
The key parameter is params. It defines the CSS properties that will be animated. Many properties can be animated at the same time:
animate({width:"70%",opacity:0.4,marginLeft:"0.6in",fontSize:"3em"});
The second parameter is duration. It specifies the speed of the animation. Possible values are "fast", "slow", "normal", or milliseconds.
Example 1
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div").animate({height:300},"slow");
$("div").animate({width:300},"slow");
$("div").animate({height:100},"slow");
$("div").animate({width:100},"slow");
});
});
</script>
Try it yourself »
Example 2
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left:"100px"},"slow");
$("div").animate({fontSize:"3em"},"slow");
});
});
</script>
Try it yourself »
HTML elements are positioned static by default and cannot be moved.
To make elements moveable, set the CSS position property to fixed, relative or absolute.
jQuery Effects
Here are some examples of effect functions in jQuery:
Function
Description
$(selector).hide()
Hide selected elements
$(selector).show()
Show selected elements
$(selector).toggle()
Toggle (between hide and show) selected elements
$(selector).slideDown()
Slide-down (show) selected elements
$(selector).slideUp()
Slide-up (hide) selected elements
$(selector).slideToggle()
Toggle slide-up and slide-down of selected elements
$(selector).fadeIn()
Fade in selected elements
$(selector).fadeOut()
Fade out selected elements
$(selector).fadeTo()
Fade out selected elements to a given opacity
$(selector).animate()
Run a custom animation on selected elements
For a full jQuery effect reference, please go to our jQuery Effect Reference.
jQuery Callback Functions
A callback function is executed after the current animation is 100% finished.
jQuery Callback Functions
A callback function is executed after the current animation (effect) is finished.
JavaScript statements are executed line by line. However, with animations, the next line of code can be run even though the animation is not finished. This can create errors.
To prevent this, you can create a callback function. The callback function will not be called until after the animation is finished.
jQuery Callback Example
Typical syntax: $(selector).hide(speed,callback)
The callback parameter is a function to be executed after the hide effect is completed:
Example with Callback
$("p").hide(1000,function(){
alert("The paragraph is now hidden");
});
Try it yourself »
Without a callback parameter, the alert box is displayed before the hide effect is completed:
Example without Callback
$("p").hide(1000);
alert("The paragraph is now hidden");
Try it yourself »
jQuery HTML Manipulation
jQuery contains powerful methods (functions) for changing and manipulating HTML elements and attributes.
Changing HTML Content
$(selector).html(content)
The html() method changes the contents (innerHTML) of matching HTML elements.
Example
$("p").html("W3Schools");
Try it yourself »
Adding HTML content
$(selector).append(content)
The append() method appends content to the inside of matching HTML elements.
$(selector).prepend(content)
The prepend() method "prepends" content to the inside of matching HTML elements.
Example
$("p").append(" W3Schools");
Try it yourself »
$(selector).after(content)
The after() method inserts HTML content after all matching elements.
$(selector).before(content)
The before() method inserts HTML content before all matching elements.
Example
$("p").after(" W3Schools.");
Try it yourself »
jQuery HTML Manipulation Methods From This Page:
Function
Description
$(selector).html(content)
Changes the (inner) HTML of selected elements
$(selector).append(content)
Appends content to the (inner) HTML of selected elements
$(selector).after(content)
Adds HTML after selected elements
For a full jQuery HTML reference, please go to our jQuery HTML Methods Reference.
jQuery CSS Manipulation
jQuery css() Method
jQuery has one important method for CSS manipulation: css()
The css() method has three different syntaxes, to perform different tasks.
css(name) - Return CSS property value
css(name,value) - Set CSS property and value
css({properties}) - Set multiple CSS properties and values
Return CSS Property
Use css(name) to return the specified CSS property value of the FIRST matched element:
Example
$(this).css("background-color");
Try it yourself »
Set CSS Property and Value
Use css(name,value) to set the specified CSS property for ALL matched elements:
Example
$("p").css("background-color","yellow");
Try it yourself »
Set Multiple CSS Property/Value Pairs
Use css({properties}) to set one or more CSS property/value pairs for the selected elements:
Example
$("p").css({"background-color":"yellow","font-size":"200%"});
Try it yourself »
jQuery height() and width() Methods
jQuery has two important methods for size manipulation.
height()
width()
Size Manipulation Examples
The height() method sets the height of all matching elements:
Example
$("#div1").height("200px");
Try it yourself »
The width() method sets the width of all matching elements:
Example
$("#div2").width("300px");
Try it yourself »
jQuery CSS Methods From this Page:
CSS Properties
Description
$(selector).css(name)
Get the style property value of the first matched element
$(selector).css(name,value)
Set the value of one style property for matched elements
$(selector).css({properties})
Set multiple style properties for matched elements
$(selector).height(value)
Set the height of matched elements
$(selector).width(value)
Set the width of matched elements
For a full jQuery CSS reference, please go to our jQuery CSS Methods Reference.
jQuery AJAX
jQuery has a rich library of methods (functions) for AJAX development.
jQuery AJAX ExampleAJAX is not a programming language.
It is just a technique for creating better and more interactive web applications.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("div").load('test1.txt');
});
});
</script>
</head>
<body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>
The example above is taken from our AJAX tutorial, but modified with jQuery syntax.
What is AJAX?
AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
You can learn more about AJAX in our AJAX tutorial.
AJAX and jQuery
jQuery provides a rich set of methods for AJAX web development.
With jQuery AJAX, you can request TXT, HTML, XML or JSON data from a remote server using both HTTP Get and HTTP Post.
And you can load remote data directly into selected HTML elements of your web page!
Write Less, Do More
The jQuery load() method is a simple (but very powerful) AJAX function. It has the following syntax:
$(selector).load(url,data,callback)
Use the selector to define the HTML element(s) to change, and the url parameter to specify a web address for your data.
Try it yourself »
Only if you want to send data to the server, you need to use the data parameter. Only if you need to trigger a function after completion, you will use the callback parameter.
Low Level AJAX
$.ajax(options) is the syntax of the low level AJAX function.
$.ajax offers more functionality than higher level functions like load, get, and post, but it is also more difficult to use.
The option parameter takes name|value pairs defining url data, passwords, data types, filters, character sets, timeout and error functions.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"test1.txt", success:function(result){
$("div").html(result);
}});
});});
</script>
</head>
<body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>
jQuery AJAX Methods From This Page:
Request
Description
$(selector).load(url,data,callback)
Load remote data into selected elements
$.ajax(options)
Load remote data into an XMLHttpRequest object
For a full jQuery AJAX reference, please go to our jQuery AJAX Methods Reference.
W3Schools jQuery Quiz
1. Which of the following is correct?
Correct Answer!
2. jQuery uses CSS selectors and XPath expressions to select elements?
Correct Answer!
3. Which sign does jQuery use as a shortcut for jQuery?
Correct Answer!
4. With jQuery, look at the following selector: $("div"). What does it select?
Correct Answer!
5. Is jQuery a library for client scripting or server scripting?
Correct Answer!
6. Is it possible to use jQuery together with AJAX?
Correct Answer!
7. The jQuery html() method works for both HTML and XML documents
You answered:
True
Wrong Answer!
8. What is the correct jQuery code to set the background color of all p elements to red?
Correct Answer!
9. With jQuery, look at the following selector: $("div.intro"). What does it select?
You answered:
The first div element with class="intro"
Wrong Answer!
10. Which jQuery method is used to hide selected elements?
Correct Answer!
11. Which jQuery method is used to set one or more style properties for selected elements?
Correct Answer!
12. Which jQuery method is used to perform an asynchronous HTTP request?
Correct Answer!
13. What is the correct jQuery code for making all div elements 100 pixels high?
Correct Answer!
14. Which statement is true?
Correct Answer!
15. What scripting language is jQuery written in?
Correct Answer!
16. Which jQuery function is used to prevent code from running, before the document is finished loading?
Correct Answer!
17. Which jQuery method should be used to deal with name conflicts?
Correct Answer!
18. Which jQuery method is used to switch between adding/removing one or more classes (for CSS) from selected elements?
Correct Answer!
19. Look at the following jQuery selector: $("div#intro .head"). What does it select?
Correct Answer!
20. Is jQuery a W3C standard?
You answered:
Yes
Wrong Answer!
12 Key Points why JQuery is Boss
1. Cross browser capability
2. Cross language capability
3. Integrated in Microsoft development products
4. Consistent coding usage
5. Consistent JavaScript library
6. Faster development time
7. JSON for faster and more efficient back end communication.
8. Consistent Ajax support
9. Low Learning Curve
10. Simplified Document Traversal
11. Not Just Objects
12. Better CSS Interaction
0 comments:
Post a Comment