Introduction to JQUERY
The jQuery library
can be added to a web page with a single line of markup.
What You Should Already
Know
Before you start studying
jQuery, you should have a basic knowledge of:
·
HTML
·
CSS
· JavaScript
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
The jQuery library is
stored a single JavaScript file, containing all the jQuery functions.
It can be added to a web
page with the following mark-up:
<head>
<script type="text/javascript" src="jquery.js"></script> </head> |
Please note that the
<script> tag should be inside the page's <head> section.
Basic jQuery Example
The following example
demonstrates the jQuery hide() function, hiding all <p> elements in an
HTML document.
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> The jQuery library can be added to a web page with a single line of markup. Adding the jQuery Library to Your Pages
The jQuery library is stored a single JavaScript file,
containing all the jQuery functions.
It can be added to a web page with the following
mark-up:
<head>
<script type="text/javascript" src="jquery.js"></script> </head>
Please note that the <script> tag should be inside
the page's <head> section.
Downloading jQuery
Two versions of jQuery are available for downloading:
one minified and one uncompressed (for debugging or reading).
Both versions can be downloaded from jQuery.com.
Alternatives to Downloading
If you don't want to store the jQuery library on your
own computer, you can use the hosted jQuery library from Google or Microsoft.
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> </head> Microsoft
<head>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script> </head> |
Downloading jQuery
Two versions of jQuery are
available for downloading: one minified and one uncompressed (for debugging or
reading).
Alternatives to Downloading
If you don't want to store
the jQuery library on your own computer, you can use the hosted jQuery library
from Google or Microsoft.
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> </head> |
Microsoft
<head>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script> </head> |
jQuery Syntax Examples
$(this).hide()
Demonstrates the jQuery hide() function, hiding the current HTML element.
Demonstrates the jQuery hide() function, hiding the current HTML element.
$("#test").hide()
Demonstrates the jQuery hide() function, hiding the element with id="test".
Demonstrates the jQuery hide() function, hiding the element with id="test".
$("p").hide()
Demonstrates the jQuery hide() function, hiding all <p> elements.
Demonstrates the jQuery hide() function, hiding all <p> elements.
$(".test").hide()
Demonstrates the jQuery hide() function, hiding all elements with class="test".
Demonstrates the jQuery hide() function, 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"
The Document Ready Function
You might have noticed that all jQuery functions, 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 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.
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 the first <p> element
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");
|
Some More Examples
Syntax
|
Description
|
$(this)
|
Current HTML element
|
$("p")
|
All <p> elements
|
$("p.intro")
|
All <p> elements with class="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"
|
Selector
|
Example
|
Selects
|
$("*")
|
All elements
|
|
$("#lastname")
|
The element with id=lastname
|
|
$(".intro")
|
All elements with class="intro"
|
|
$("p")
|
All p elements
|
|
.class.class
|
$(".intro.demo")
|
All elements with the classes "intro" and
"demo"
|
$("p:first")
|
The first p element
|
|
$("p:last")
|
The last p element
|
|
$("tr:even")
|
All even tr elements
|
|
$("tr:odd")
|
All odd tr elements
|
|
$("ul li:eq(3)")
|
The fourth element in a list (index starts at 0)
|
|
$("ul li:gt(3)")
|
List elements with an index greater than 3
|
|
$("ul li:lt(3)")
|
List elements with an index less than 3
|
|
$("input:not(:empty)")
|
All input elements that are not empty
|
|
$(":header")
|
All header elements h1, h2 ...
|
|
$(":animated")
|
All animated elements
|
|
$(":contains('W3Schools')")
|
All elements which contains the text
|
|
$(":empty")
|
All elements with no child (elements) nodes
|
|
:hidden
|
$("p:hidden")
|
All hidden p elements
|
$("table:visible")
|
All visible tables
|
|
s1,s2,s3
|
$("th,td,.intro")
|
All elements with matching selectors
|
$("[href]")
|
All elements with a href attribute
|
|
$("[href='default.htm']")
|
All elements with a href attribute value equal to
"default.htm"
|
|
$("[href!='default.htm']")
|
All elements with a href attribute value not equal to
"default.htm"
|
|
$("[href$='.jpg']")
|
All elements with a href attribute value ending with
".jpg"
|
|
$(":input")
|
All input elements
|
|
$(":text")
|
All input elements with type="text"
|
|
$(":password")
|
All input elements with type="password"
|
|
$(":radio")
|
All input elements with type="radio"
|
|
$(":checkbox")
|
All input elements with type="checkbox"
|
|
$(":submit")
|
All input elements with type="submit"
|
|
$(":reset")
|
All input elements with type="reset"
|
|
$(":button")
|
All input elements with type="button"
|
|
$(":image")
|
All input elements with type="image"
|
|
$(":file")
|
All input elements with type="file"
|
|
$(":enabled")
|
All enabled input elements
|
|
$(":disabled")
|
All disabled input elements
|
|
$(":selected")
|
All selected input elements
|
|
$(":checked")
|
All checked input elements
|
jQuery Event Functions
The jQuery event handling functions are core functions in
jQuery.
Event handlers are functions 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
functions 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>
|
In the example above, a function is called when the click
event for the button is triggered:
$("button").click(function()
{..some code... } )
The function 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.
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
|
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(); }); |
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); }); |
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(); }); |
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(); }); |
slideUp() Example
$(".flip").click(function(){
$(".panel").slideUp() }) |
slideToggle() Example
$(".flip").click(function(){
$(".panel").slideToggle(); }); |
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); }); |
fadeOut() Example
$("button").click(function(){
$("div").fadeOut(4000); }); |
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 defines the time used to apply the animation. I takes
the values "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> |
||
Example 2
<script type="text/javascript">
$(document).ready(function(){ $("button").click(function(){ $("div").animate({left:"100px"},"slow"); $("div").animate({fontSize:"3em"},"slow"); }); }); </script> |
||
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
|
Method
|
Description
|
Performs a custom animation (of a set of CSS
properties) for selected elements
|
|
Removes all queued functions for the selected element
|
|
delay()
|
Sets a delay for all queued functions for the selected
element
|
dequeue()
|
Runs the next queued functions for the selected
element
|
Gradually changes the opacity, for selected elements,
from hidden to visible
|
|
Gradually changes the opacity, for selected elements,
from visible to hidden
|
|
Gradually changes the opacity, for selected elements,
to a specified opacity
|
|
Hides selected elements
|
|
queue()
|
Shows the queued functions for the selected element
|
Shows hidden selected elements
|
|
Gradually changes the height, for selected elements,
from hidden to visible
|
|
Toggles between slideUp() and slideDown() for selected
elements
|
|
Gradually changes the height, for selected elements,
from visible to hidden
|
|
Stops a running animation on selected elements
|
|
Toggles between hide() and show(), or custom
functions, for selected elements
|
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"); }); |
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");
jQuery contains powerful methods 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");
Adding
HTML content
$(selector).append(content)
The append() function appends content to the inside of
matching HTML elements.
$(selector).prepend(content)
The prepend() function "prepends" content to
the inside of matching HTML elements.
Example
$("p").append(" W3Schools");
$(selector).after(content)
The after() function inserts HTML content after all
matching elements.
$(selector).before(content)
The before() function inserts HTML content before all
matching elements.
Example
$("p").after("
W3Schools.");
jQuery
HTML Manipulation - 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).prepend(content)
"Prepends" content to the (inner) HTML of selected elements
$(selector).after(content) Adds HTML after selected elements
$(selector).before(content) Adds HTML before selected elements
|
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
Example
$(this).css("background-color");
|
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");
|
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%"});
|
jQuery has two important methods for size manipulation.
·
height()
·
width()
The height() method sets the height of all matching
elements:
Example
$("#div1").height("200px");
|
The width() method sets the width of all matching
elements:
Example
$("#div2").width("300px");
|
jQuery CSS Functions - From this Page
CSS Properties
|
Description
|
|
$(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).css(name)
|
Get the style property value of the first matched
element
|
|
$(selector).height(value)
|
Set the height of matched elements
|
|
$(selector).width(value)
|
Set the width of matched elements
|
|
Method
|
Description
|
|
Adds one or more classes to selected elements
|
||
Sets or returns one or more style properties for
selected elements
|
||
Checks if any of the selected elements have a
specified class
|
||
Sets or returns the height of selected elements
|
||
Sets or returns the position (relative to the
document) for selected elements
|
||
Returns the first parent element that is positioned
|
||
Returns the position (relative to the parent element)
of the first selected element
|
||
Removes one or more classes from selected elements
|
||
Sets or returns the horizontal position of the
scrollbar for the selected elements
|
||
Sets or returns the vertical position of the scrollbar
for the selected elements
|
||
Toggles between adding/removing one or more classes
from selected elements
|
||
Sets or returns the width of selected elements
|
||
jQuery has a rich library
of functions (methods) for AJAX development.
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.
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.
AJAX and jQuery
jQuery provides a rich set of methods (functions) 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 function 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.
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.
jQuery AJAX Requests
Request
|
Description
|
$(selector).load(url,data,callback)
|
Load remote data into selected elements
|
$.ajax(options)
|
Load remote data into an XMLHttpRequest object
|
$.get(url,data,callback,type)
|
Load remote data using HTTP GET
|
$.post(url,data,callback,type)
|
Load remote data using HTTP POST
|
$.getJSON(url,data,callback)
|
Load remote JSON data using HTTP GET
|
$.getScript(url,callback)
|
Load and execute a remote JavaScript file
|
(selector) jQuery element
selector
(url) The URL (address) of data to be loaded
(data) Key/value pairs of data to send to the server
(callback) Function to be executed when data is loaded
(type) Type of data to be returned
(html,xml,json,jasonp,script,text)
(options) All key/value pairs of options for a complete
AJAX request
No comments:
Post a Comment