JQuery
Introduction
jQuery is
a lightweight, "write less, do more", JavaScript library.
The
purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery
takes a lot of common tasks that require many lines of JavaScript code to
accomplish, and wraps them into methods that you can call with a single line of
code.
jQuery
also simplifies a lot of the complicated things from JavaScript, like AJAX
calls and DOM manipulation.
The
jQuery library contains the following features:
- HTML/DOM manipulation
- CSS manipulation
- HTML event methods
- Effects and animations
- AJAX
- Utilities
Adding jQuery to Your Web Pages
There are
several ways to start using jQuery on your web site. You can:
- Download the jQuery library from jQuery.com
- Include jQuery from a CDN, like Google
Downloading jQuery
There are
two versions of jQuery available for downloading:
- Production version - this is for your live website because it has been minified and compressed
- Development version - this is for testing and development (uncompressed and readable code)
Both versions can be downloaded from jQuery.com.
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<script src="jquery-1.10.2.min.js"></script>
</head>
JQuery Syntax
The
jQuery syntax is tailor made for selecting HTML elements and performing
some action on the element(s).
Basic
syntax is: $(selector).action()
- A $ sign to define/access jQuery
- A (selector) to "query (or find)" HTML elements
- A jQuery action() to be performed on the element(s)
Examples:
$(this).hide()
- hides the current element.
$("p").hide()
- hides all <p> elements.
$(".test").hide()
- hides all elements with class="test".
$("#test").hide()
- hides the element with id="test".
This is
to prevent any jQuery code from running before the document is finished loading
(is ready).
It is
good practice to wait for the document to be fully loaded and ready before
working with it. This also allows you to have your JavaScript code before the
body of your document, in the head section.
Here are
some examples of actions that can fail if methods are run before the document
is fully loaded:
- Trying to hide an element that is not created yet
- Trying to get the size of an image that is not loaded yet
·
Tip: The
jQuery team has also created an even shorter method for the document ready
event:
·
$(function(){
// jQuery methods go here...
});
// jQuery methods go here...
});
jQuery Selectors
jQuery selectors are one of the most important parts of the
jQuery library.
jQuery
selectors allow you to select and manipulate HTML element(s).
jQuery
selectors are used to "find" (or select) HTML elements based on their
id, classes, types, attributes, values of attributes and much more. It's based
on the existing CSS Selectors, and in addition, it has some
own custom selectors.
All
selectors in jQuery start with the dollar sign and parentheses: $().
All selectors in jQuery start with the dollar sign and
parentheses: $().
The element Selector
The
jQuery element selector selects elements based on the element name.
You can
select all <p> elements on a page like this:
$("p")
When a user clicks on a button, all <p> elements will be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
$("button").click(function(){
$("p").hide();
});
});
<script>
$(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>
The #id Selector
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the element:
$("#test")
ExampleWhen a user clicks on a button, the element with id="test" will be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
$("button").click(function(){
$("#test").hide();
});
The .class Selector
The jQuery class selector finds elements with a specific class.To find elements with a specific class, write a period character, followed by the name of the class:
$(".test")
ExampleWhen a user clicks on a button, the elements with class="test" will be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
$("button").click(function(){
$(".test").hide();
});
});
jQuery Selectors
Selector
|
Example
|
Selects
|
$("*")
|
All
elements
|
|
$("#lastname")
|
The
element with id="lastname"
|
|
$(".intro")
|
All
elements with class="intro"
|
|
$(".intro,.demo")
|
All
elements with the class "intro" or "demo"
|
|
$("p")
|
All
<p> elements
|
|
$("h1,div,p")
|
All
<h1>, <div> and <p> elements
|
|
$("p:first")
|
The
first <p> element
|
|
$("p:last")
|
The
last <p> element
|
|
$("tr:even")
|
All
even <tr> elements
|
|
$("tr:odd")
|
All odd
<tr> elements
|
|
$("p:first-child")
|
All
<p> elements that are the first child of their parent
|
|
$("p:first-of-type")
|
All
<p> elements that are the first <p> element of their parent
|
|
$("p:last-child")
|
All
<p> elements that are the last child of their parent
|
|
$("p:last-of-type")
|
All
<p> elements that are the last <p> element of their parent
|
|
$("p:nth-child(2)")
|
All
<p> elements that are the 2nd child of their parent
|
|
$("p:nth-last-child(2)")
|
All
<p> elements that are the 2nd child of their parent, counting from the
last child
|
|
$("p:nth-of-type(2)")
|
All
<p> elements that are the 2nd <p> element of their parent
|
|
$("p:nth-last-of-type(2)")
|
All
<p> elements that are the 2nd <p> element of their parent,
counting from the last child
|
|
$("p:only-child")
|
All
<p> elements that are the only child of their parent
|
|
$("p:only-of-type")
|
All
<p> elements that are the only child, of its type, of their parent
|
|
$("div
> p")
|
All
<p> elements that are a direct child of a <div> element
|
|
$("div
p")
|
All
<p> elements that are descendants of a <div> element
|
|
$("div
+ p")
|
The
<p> element that are next to each <div> elements
|
|
$("div
~ p")
|
All
<p> elements that are siblings of a <div> element
|
|
$("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
|
|
$(":focus")
|
The
element that currently has focus
|
|
$(":contains('Hello')")
|
All
elements which contains the text "Hello"
|
|
$("div:has(p)")
|
All
<div> elements that have a <p> element
|
|
$(":empty")
|
All
elements that are empty
|
|
$(":parent")
|
All
elements that are a parent of another element
|
|
$("p:hidden")
|
All
hidden <p> elements
|
|
$("table:visible")
|
All
visible tables
|
|
$(":root")
|
The
document’s root element
|
|
$("p:lang(de)")
|
All
<p> elements with a lang attribute value starting with "de"
|
|
$("[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"
|
|
$("[title|='Tomorrow']")
|
All
elements with a title attribute value equal to 'Tomorrow', or starting with
'Tomorrow' followed by a hyphen
|
|
$("[title^='Tom']")
|
All
elements with a title attribute value starting with "Tom"
|
|
$("[title~='hello']")
|
All
elements with a title attribute value containing the word "hello"
|
|
$("[title*='hello']")
|
All
elements with a title attribute value containing the string "hello"
|
|
$(":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
|
<script>
$(document).ready(function(){
$("input").focus();
$(":focus").css("background-color","yellow");
});
</script>
JQuery Event Methods
Event
methods trigger or attach a function to an event handler for the selected
elements.
The
following table lists all the jQuery methods used to handle events.
Method
|
Description
|
Attaches
event handlers to elements
|
|
Attaches/Triggers
the blur event
|
|
Attaches/Triggers
the change event
|
|
Attaches/Triggers
the click event
|
|
Attaches/Triggers
the double click event
|
|
Attaches
a handler to current, or future, specified child elements of the matching
elements
|
|
Removed
in version 1.9. Removes all event handlers added with the live() method
|
|
Deprecated
in version 1.8. Attaches/Triggers the error event
|
|
The
current DOM element within the event bubbling phase
|
|
Contains
the optional data passed to an event method when the current executing
handler is bound
|
|
Returns
the element where the currently-called jQuery event handler was attached
|
|
Returns
whether event.preventDefault() was called for the event object
|
|
Returns
whether event.stopImmediatePropagation() was called for the event object
|
|
Returns
whether event.stopPropagation() was called for the event object
|
|
Returns
the namespace specified when the event was triggered
|
|
Returns
the mouse position relative to the left edge of the document
|
|
Returns
the mouse position relative to the top edge of the document
|
|
Prevents
the default action of the event
|
|
Returns which
element being entered or exited on mouse movement.
|
|
Contains
the last/previous value returned by an event handler triggered by the
specified event
|
|
Prevents
other event handlers from being called
|
|
Prevents
the event from bubbling up the DOM tree, preventing any parent handlers from
being notified of the event
|
|
Returns
which DOM element triggered the event
|
|
Returns
the number of milliseconds since January 1, 1970, when the event is triggered
|
|
Returns
which event type was triggered
|
|
Returns
which keyboard key or mouse button was pressed for the event
|
|
Attaches/Triggers
the focus event
|
|
Attaches
an event handler to the focusin event
|
|
Attaches
an event handler to the focusout event
|
|
Attaches
two event handlers to the hover event
|
|
Attaches/Triggers
the keydown event
|
|
Attaches/Triggers
the keypress event
|
|
Attaches/Triggers
the keyup event
|
|
Removed
in version 1.9. Adds one or more event handlers to current, or future,
selected elements
|
|
Deprecated
in version 1.8. Attaches an event handler to the load event
|
|
Attaches/Triggers
the mousedown event
|
|
Attaches/Triggers
the mouseenter event
|
|
Attaches/Triggers
the mouseleave event
|
|
Attaches/Triggers
the mousemove event
|
|
Attaches/Triggers
the mouseout event
|
|
Attaches/Triggers
the mouseover event
|
|
Attaches/Triggers
the mouseup event
|
|
Removes
event handlers attached with the on() method
|
|
Attaches
event handlers to elements
|
|
Adds
one or more event handlers to selected elements. This handler can only be
triggered once per element
|
|
Takes
an existing function and returns a new one with a particular context
|
|
Specifies
a function to execute when the DOM is fully loaded
|
|
Attaches/Triggers
the resize event
|
|
Attaches/Triggers
the scroll event
|
|
Attaches/Triggers
the select event
|
|
Attaches/Triggers
the submit event
|
|
Removed
in version 1.9. Attaches two or more functions to toggle between for the
click event
|
|
Triggers
all events bound to the selected elements
|
|
Triggers
all functions bound to a specified event for the selected elements
|
|
Removes
an added event handler from selected elements
|
|
Removes
an event handler to selected elements, now or in the future
|
|
Deprecated
in version 1.8. Attaches an event handler to the unload event
|
Example:
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").hover(function(){
$("p").css("background-color","yellow");
},function(){
$("p").css("background-color","pink");
});
});
</script>
</head>
<body>
<p>Hover the mouse
pointer over this paragraph.</p>
</body>
</html>
JQuery Effects
Jquery Fade
Jquery Hide/Show
Jquery Slide
Jquery Animate
Jquery stop()
Jqury callback
Jquery Chaining
JQuery HTML
Jquery Get
Jquery Set
Jquery Add
Jquery Remove
Jquery CSS classes
Jquery css()
Jquery Dimensions
JQuery - AJAX Introduction
AJAX is the art of exchanging data with a server, and
updating parts of a web page - without reloading the whole page.
AJAX =
Asynchronous JavaScript and XML.
In short;
AJAX is about loading data in the background and display it on the webpage,
without reloading the whole page.
Examples
of applications using AJAX: Gmail, Google Maps, Youtube, and Facebook tabs.
You can
learn more about AJAX in our AJAX tutorial.
What About jQuery and AJAX?
Query
provides several methods for AJAX functionality.
With the
jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote
server using both HTTP Get and HTTP Post - And you can load the external data
directly into the selected HTML elements of your web page!
Without jQuery, AJAX coding
can be a bit tricky!
Writing regular AJAX code can be a bit tricky, because different browsers have different syntax for AJAX implementation. This means that you will have to write extra code to test for different browsers. However, the jQuery team has taken care of this for us, so that we can write AJAX functionality with only one single line of code.
Writing regular AJAX code can be a bit tricky, because different browsers have different syntax for AJAX implementation. This means that you will have to write extra code to test for different browsers. However, the jQuery team has taken care of this for us, so that we can write AJAX functionality with only one single line of code.
JQuery - AJAX load() Method
JQuery load() Method
The
jQuery load() method is a simple, but powerful AJAX method.
The
load() method loads data from a server and puts the returned data into the
selected element.
Syntax:
$(selector).load(URL,data,callback);
The
required URL parameter specifies the URL you wish to load.
The
optional data parameter specifies a set of querystring key/value pairs to send
along with the request.
The
optional callback parameter is the name of a function to be executed after the
load() method is completed.
The
optional callback parameter specifies a callback function to run when the
load() method is completed. The callback function can have different
parameters:
- responseTxt - contains the resulting content if the call succeed
- statusTxt - contains the status of the call
- xhr - contains the XMLHttpRequest object
The
following example displays an alert box after the load() method completes. If
the load() method has succeed, it displays "External content loaded
successfully!", and if it fails it displays an error message:
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("External content loaded
successfully!");
if(statusTxt=="error")
alert("Error: "+xhr.status+":
"+xhr.statusText);
});
});
});
</script>
JQuery - AJAX get() and post() Methods
Two
commonly used methods for a request-response between a client and server are:
GET and POST.
- GET - Requests data from a specified resource
- POST - Submits data to be processed to a specified resource
GET is
basically used for just getting (retrieving) some data from the server. Note:
The GET method may return cached data.
POST can
also be used to get some data from the server. However, the POST method NEVER
caches data, and is often used to send data along with the request.
JQuery $.get() Method
Syntax:
$.get(URL,callback);
The
required URL parameter specifies the URL you wish to request.
The
optional callback parameter is the name of a function to be executed if the
request succeeds.
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.asp",function(data,status){
alert("Data: " +
data + "\nStatus: " + status);
});
});
});
</script>
The first callback parameter
holds the content of the page requested, and the second callback parameter
holds the status of the request.
JQuery $.post() Method
The
$.post() method requests data from the server using an HTTP POST request.
Syntax:
$.post(URL,data,callback);
The
required URL parameter specifies the URL you wish to request.
The
optional data parameter specifies some data to send along with the request.
The
optional callback parameter is the name of a function to be executed if the
request succeeds.
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name:"Donald
Duck",
city:"Duckburg"
},
function(data,status){
alert("Data: " +
data + "\nStatus: " + status);
});
});
});
</script>
JQuery - The noConflict() Method
What if you wish to use other frameworks on your pages,
while still using jQuery?
As you
already know; jQuery uses the $ sign as a shortcut for jQuery.
What if
other JavaScript frameworks also use the $ sign as a shortcut?
Some other popular JavaScript frameworks are: MooTools,
Backbone, Sammy, Cappuccino, Knockout, JavaScript MVC, Google Web Toolkit,
Google Closure, Ember, Batman, and Ext
JS.
Some of the other frameworks also use the $ character as a shortcut
(just like jQuery), and then you suddenly have two different frameworks using
the same shortcut, which might result in that your scripts stop working.
The jQuery team have already thought about this, and implemented the noConflict() method.
The
noConflict() method releases the hold on the $ shortcut identifier, so that other
scripts can use it.
You can
of course still use jQuery, simply by writing the full name instead of the
shortcut
You can also create your own shortcut very easily. The
noConflict() method returns a reference to jQuery, that you can save in a
variable, for later use. Here is an example:
var jq = $.noConflict();
jq(document).ready(function(){
jq("button").click(function(){
jq("p").text("jQuery is still working!");
});
});
jq(document).ready(function(){
jq("button").click(function(){
jq("p").text("jQuery is still working!");
});
});
è
If you have a block of jQuery code which uses the $
shortcut and you do not want to change it all, you can pass the $ sign in as a
parameter to the ready method. This allows you to access jQuery using $, inside
this function - outside of it, you will have to use "jQuery":
$.noConflict();
jQuery(document).ready(function($){
$("button").click(function(){
$("p").text("jQuery is still working!");
});
});
jQuery(document).ready(function($){
$("button").click(function(){
$("p").text("jQuery is still working!");
});
});
Using load() method
Syntax:
$(selector).load(URL,data,callback);
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("External content loaded successfully!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
});
Using
$.ajax()
Syntax:-
$.ajax({name:value,
name:value, ... })
The
parameters specifies one or more name/value pairs for the AJAX request.
Possible
names/values in the table below:
Name
|
Value/Description
|
async
|
A
Boolean value indicating whether the request should be handled asynchronous
or not. Default is true
|
beforeSend(xhr)
|
A
function to run before the request is sent
|
cache
|
A
Boolean value indicating whether the browser should cache the requested
pages. Default is true
|
complete(xhr,status)
|
A
function to run when the request is finished (after success and error
functions)
|
contentType
|
The
content type used when sending data to the server. Default is:
"application/x-www-form-urlencoded"
|
context
|
Specifies
the "this" value for all AJAX related callback functions
|
data
|
Specifies
data to be sent to the server
|
dataFilter(data,type)
|
A
function used to handle the raw response data of the XMLHttpRequest
|
dataType
|
The
data type expected of the server response.
|
error(xhr,status,error)
|
A
function to run if the request fails.
|
global
|
A
Boolean value specifying whether or not to trigger global AJAX event handles
for the request. Default is true
|
ifModified
|
A
Boolean value specifying whether a request is only successful if the response
has changed since the last request. Default is: false.
|
jsonp
|
A
string overriding the callback function in a jsonp request
|
jsonpCallback
|
Specifies
a name for the callback function in a jsonp request
|
password
|
Specifies
a password to be used in an HTTP access authentication request.
|
processData
|
A Boolean
value specifying whether or not data sent with the request should be
transformed into a query string. Default is true
|
scriptCharset
|
Specifies
the charset for the request
|
success(result,status,xhr)
|
A
function to be run when the request succeeds
|
timeout
|
The
local timeout (in milliseconds) for the request
|
traditional
|
A
Boolean value specifying whether or not to use the traditional style of param
serialization
|
type
|
Specifies
the type of request. (GET or POST)
|
url
|
Specifies
the URL to send the request to. Default is the current page
|
username
|
Specifies
a username to be used in an HTTP access authentication request
|
xhr
|
A
function used for creating the XMLHttpRequest object
|
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
alert("External content loaded
successfully!");
$("#div1").html(result);
}});
});
});
JQuery AJAX Methods
AJAX is
the art of exchanging data with a server, and update parts of a web page -
without reloading the whole page.
The
following table lists all the jQuery AJAX methods:
Method
|
Description
|
Performs an async AJAX request
|
|
$.ajaxPrefilter()
|
Handle custom Ajax options or modify existing options
before each request is sent and before they are processed by $.ajax()
|
Sets the default values for future AJAX requests
|
|
$.ajaxTransport()
|
Creates an object that handles the actual transmission of
Ajax data
|
Loads JSON-encoded data from a server using a HTTP GET
request
|
|
Loads (and executes) a JavaScript from a server using an
AJAX HTTP GET request
|
|
Creates a serialized representation of an array or object
(can be used as URL query string for AJAX requests)
|
|
$.post()
|
Loads data from a server using an AJAX HTTP POST request
|
Specifies a function to run when the AJAX request
completes
|
|
Specifies a function to run when the AJAX request
completes with an error
|
|
Specifies a function to run before the AJAX request is
sent
|
|
Specifies a function to run when the first AJAX request
begins
|
|
Specifies a function to run when all AJAX requests have
completed
|
|
Specifies a function to run when an AJAX request completes
successfully
|
|
Loads data from a server and puts the returned data into
the selected element
|
|
Encodes a set of form elements as a string for submission
|
|
Encodes a set of form elements as an array of names and
values
|




0 comments:
Post a Comment