jquery referance - jan zumwalt
TRANSCRIPT
-
8/3/2019 JQUERY Referance - Jan Zumwalt
1/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 1 of 28
These notes have been heavily reformatted and edited. Some material came from the following authors,
Author:Jrn Zaefferer Link:http://jquery.bassistance.de/jquery-getting-started.html
Site: http://www.tutorialspoint.com
-
8/3/2019 JQUERY Referance - Jan Zumwalt
2/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 2 of 28
Blank Page
-
8/3/2019 JQUERY Referance - Jan Zumwalt
3/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 3 of 28
Table of Contents
Introduction............................. ......................... .......................... ...................... ......................... ......................... 4Setup ......................... ....................... ......................... ......................... ......................... ...................... .............. 4Hello World ......................... ...................... ......................... ......................... ...................... ......................... ...... 4
Selectors (page elements)............ ...................... ......................... ......................... ...................... ....................... 5DOM Attributes ..................... ...................... ......................... ......................... ...................... ......................... ...... 6DOM Traversing Methods........ ........................ ......................... ....................... ......................... ......................... 7CSS Methods ........................ ...................... ......................... ......................... ...................... ......................... ...... 8DOM Manipulation Methods .................... ......................... ...................... ......................... ......................... ......... 8Event Handling ..................... ...................... ......................... ......................... ...................... ......................... ...... 9AJAX Methods ......................... ........................ ......................... ....................... ......................... ......................... 9Built In Effect Methods ....................... ......................... ......................... ......................... ...................... ............ 10Additional Effects (UI Library)......................................................................................................................... 11Using selectors and events............................................................................................................................. 12Using Ajax........................................................................................................................................................ 14Using Animation Effects.................................................................................................................................. 16Using the tablesorter plugin............................................................................................................................ 16Writing your own plugins ........................ ......................... ...................... ......................... ......................... ....... 17Optional Settings..................... ........................ ......................... ....................... ......................... ....................... 19
$(document).ready Method................ ......................... ......................... ......................... ...................... ............ 19Selectors....................... ......................... ......................... ...................... ......................... ......................... ....... 19Sliding Effect ......................... ......................... .......................... ...................... ......................... ....................... 19Sliding Example ..................... ........................ ......................... ....................... ......................... ....................... 20Fade Effect............................. ........................ ......................... ....................... ......................... ....................... 21Animation Efftect ......................... ...................... ......................... ......................... ....................... .................... 21Create Tab Control........ ......................... ......................... ...................... ......................... ......................... ....... 22Create Carousel ..................... ........................ ......................... ....................... ......................... ....................... 24
Next steps .................... ....................... ......................... ......................... ......................... ...................... ............ 26
-
8/3/2019 JQUERY Referance - Jan Zumwalt
4/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 4 of 28
Introduction
JQuery is a javascript library, which has wide range of actions such as Event handling, animation, html documenttraversing and Ajax interaction for web development. JQuery simplifies javascript programming.
Setup
To start, we need a copy of the jQuery library, which we can get from thehttp://docs.jquery.com/Downloading_jQuery The http://docs.jquery.com/images/c/c7/Jquery-starterkit.zipStarterKit provides some markup and CSS to work with. After downloading and extracting its content we put
jquery.js into the same directory and open starterkit.html and custom.js with your favorite editor and starterkit.htmlwith a browser.
Hello World
We start with an empty html page:
// we will add our javascript code here
This page just loads the jquery.js library (make sure the URL points to where you stored your copy of jquery! Thisexample assumes that you store it in the same directory as this example file). Two comments indicate where wewill expand this template with code.
As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we needto make sure that we start adding events etc. as soon as the DOM is ready.
To do this, we register a ready event for the document.
$(document).ready(function() {
// do stuff when DOM is ready
});
Putting an alert into that function does not make much sense, as an alert does not require the DOM to be loaded.So lets try something a little more sophisticated: Show an alert when clicking a link.
Add the following to the :
Link
Now update the $(document).ready handler:
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
This should show the alert as soon as you click on the link. You are ready now to copy and paste this script intoyour custom.js file. Then, open starterkit.html in the browser and click any link. You should see a pop-up windowwith "Hello world!" message regardless of what link was clicked.
Let's have a look at what we are doing: $("a") is a jQuery selector, in this case, it selects all a elements. $ itself is
an alias for the jQuery "class", therefore $() constructs a new jQuery object. The click() function we call next is a
-
8/3/2019 JQUERY Referance - Jan Zumwalt
5/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 5 of 28
method of the jQuery object. It binds a click event to all selected elements (in this case, a single anchor element)and executes the provided function when the event occurs.
This is similar to the following code:
Link
The difference is quite obvious: We don't need to write an onclick for every single element. We have a cleanseparation of structure (HTML) and behavior (JS), just as we separate structure and presentation by using CSS.
With this in mind, we explore selectors and events a little further.
Selectors (page elements)
Following table lists down few basic selectors and explains them with examples.
Selector Description
Name Selects all elements which match with the given element Name.
#ID Selects a single element which matches with the given ID
.Class Selects all elements which match with the given Class.
Universal (*) Selects all elements available in a DOM.
Multiple Elements E, F, G Selects the combined results of all the specified selectors E, F or G.
Similar to above syntax and examples, following examples would give you understanding on using different type ofother useful selectors:
$('*'): This selector selects all elements in the document. $("p > *"): This selector selects all elements that are children of a paragraph element. $("#specialID"): This selector function gets the element with id="specialID". $(".specialClass"): This selector gets all the elements that have the class ofspecialClass. $("li:not(.myclass)"): Selects all elements matched by that do not have class="myclass".
$("a#specialID.specialClass"): This selector matches links with an id of specialID and a class ofspecialClass.
$("p a.specialClass"): This selector matches links with a class of specialClass declared within
elements.
$("ul li:first"): This selector gets only the first element of the . $("#container p"): Selects all elements matched by
that are descendants of an element that has an
id ofcontainer.
$("li > ul"): Selects all elements matched by that are children of an element matched by $("strong + em"): Selects all elements matched by that immediately follow a sibling element
matched by .
$("p ~ ul"): Selects all elements matched by that follow a sibling element matched by
. $("code, em, strong"): Selects all elements matched by or or . $("p strong, .myclass"): Selects all elements matched by that are descendants of an element
matched by
as well as all elements that have a class ofmyclass.
$(":empty"): Selects all elements that have no children. $("p:empty"): Selects all elements matched by
that have no children. $("div[p]"): Selects all elements matched by that contain an element matched by
. $("p[.myclass]"): Selects all elements matched by
that contain an element with a class ofmyclass. $("a[@rel]"): Selects all elements matched by that have a rel attribute. $("input[@name=myname]"): Selects all elements matched by that have a name value exactly
equal to myname.
$("input[@name^=myname]"): Selects all elements matched by that have a name valuebeginning with myname.
$("a[@rel$=self]"): Selects all elements matched by
that have a class value ending with bar $("a[@href*=domain.com]"): Selects all elements matched by that have an href value containing
domain.com.
$("li:even"): Selects all elements matched by that have an even index value. $("tr:odd"): Selects all elements matched by that have an odd index value.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
6/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 6 of 28
$("li:first"): Selects the first element. $("li:last"): Selects the last element. $("li:visible"): Selects all elements matched by that are visible. $("li:hidden"): Selects all elements matched by that are hidden. $(":radio"): Selects all radio buttons in the form. $(":checked"): Selects all checked boxex in the form. $(":input"): Selects only form elements (input, select, textarea, button). $(":text"): Selects only text elements (input[type=text]). $("li:eq(2)"): Selects the third element $("li:eq(4)"): Selects the fifth element $("li:lt(2)"): Selects all elements matched by element before the third one; in other words, the first
two elements.
$("p:lt(3)"): selects all elements matched by
elements before the fourth one; in other words the firstthree
elements.
$("li:gt(1)"): Selects all elements matched by after the second one. $("p:gt(2)"): Selects all elements matched by
after the third one. $("div/p"): Selects all elements matched by
that are children of an element matched by . $("div//code"): Selects all elements matched by that are descendants of an element matched by
.
$("//p//a"): Selects all elements matched by that are descendants of an element matched by
$("li:first-child"): Selects all elements matched by that are the first child of their parent. $("li:last-child"): Selects all elements matched by that are the last child of their parent. $(":parent"): Selects all elements that are the parent of another element, including text. $("li:contains(second)"): Selects all elements matched by that contain the text second.
DOM Attributes
Following table lists down few useful methods which you can use to manipulate attributes and properties:
Methods Description
attr( properties ) Set a key/value object as properties to all matched elements.
attr( key, fn ) Set a single property to a computed value, on all matched elements.
removeAttr( name ) Remove an attribute from each of the matched elements.
hasClass( class ) Returns true if the specified class is present on at least one of the set of matched elements.
removeClass( class ) Removes all or the specified class(es) from the set of matched elements.
toggleClass( class ) Adds the specified class if it is not present, removes the specified class if it is present.
html( ) Get the html contents (innerHTML) of the first matched element.
html( val ) Set the html contents of every matched element.
text( ) Get the combined text contents of all matched elements.
text( val ) Set the text contents of all matched elements.
val( ) Get the input value of the first matched element.
val( val )
Set the value attribute of every matched element if it is called on but if it is calledon with the passed value then passed option would be selected, if it iscalled on check box or radio box then all the matching check box and radiobox would be
checked.
Similar to above syntax and examples, following examples would give you understanding on using various attributemethods in different situation:
$("#myID").attr("custom") : This would return value of attribute custom for the first element matchingwith ID myID.
$("img").attr("alt", "Sample Image"): This sets the alt attribute of all the images to a new value"Sample Image".
$("input").attr({ value: "", title: "Please enter a value" }); : Sets the value of all elementsto the empty string, as well as sets the title to the string Please enter a value.
$("a[href^=http://]").attr("target","_blank"): Selects all links with an href attribute starting withhttp://and set its target attribute to_blank
$("a").removeAttr("target") : This would remove targetattribute of all the links.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
7/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 7 of 28
$("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This wouldmodify the disabled attribute to the value "disabled" while clicking Submit button.
$("p:last").hasClass("selected"): This return true if last
tag has associated classselected. $("p").text(): Returns string that contains the combined text contents of all matched
elements. $("p").text("Hello World"): This would set "Hello World" as text content of the
matching
elements
$("p").html() : This returns the HTML content of the all matching paragraphs.
$("div").html("Hello World") : This would set the HTML content of all matching to Hello World. $("input:checkbox:checked").val() : Get the first value from a checked checkbox $("input:radio[name=bar]:checked").val(): Get the first value from a set of radio buttons $("button").val("Hello") : Sets the value attribute of every matched element . $("input").val("on") : This would check all the radio or check box button whose value is "on". $("select").val("Orange") : This would select Orange option in a dropdown box with options Orange,
Mango and Banana.
$("select").val("Orange", "Mango") : This would select Orange and Mango options in a dropdown boxwith options Orange, Mango and Banana.
DOM Traversing Methods
Following table lists down useful methods which you can use to filter out various elements from a list of DOMelements:
Selector Description
eq( index ) Reduce the set of matched elements to a single element.
filter( selector ) Removes all elements from the set of matched elements that do not match the specifiedselector(s).
filter( fn ) Removes all elements from the set of matched elements that do not match the specifiedfunction.
is( selector ) Checks the current selection against an expression and returns true, if at least oneelement of the selection fits the given selector.
map( callback ) Translate a set of elements in the jQuery object into another set of values in a jQueryarray (which may, or may not contain elements).
not( selector ) Removes elements matching the specified selector from the set of matched elements.slice( start, [end] ) Selects a subset of the matched elements.
Following table lists down other useful methods which you can use to locate various elements in a DOM:
Selector Description
add( selector ) Adds more elements, matched by the given selector, to the set of matched elements.
andSelf( ) Add the previous selection to the current selection.
children( [selector])Get a set of elements containing all of the unique immediate children of each of thematched set of elements.
closest( selector )Get a set of elements containing the closest parent element that matches the specifiedselector, the starting element included.
contents( )Find all the child nodes inside the matched elements (including text nodes), or thecontent document, if the element is an iframe.
end( )Revert the most recent 'destructive' operation, changing the set of matched elements toits previous state .
find( selector ) Searches for descendent elements that match the specified selectors.
next( [selector] )Get a set of elements containing the unique next siblings of each of the given set ofelements.
nextAll( [selector] ) Find all sibling elements after the current element.
offsetParent( ) Returns a jQuery collection with the positioned parent of the first matched element.
parent( [selector] )Get the direct parent of an element. If called on a set of elements, parent returns a set oftheir unique direct parent elements.
parents( [selector] )Get a set of elements containing the unique ancestors of the matched set of elements(except for the root element).
prev( [selector] )
Get a set of elements containing the unique previous siblings of each of the matched set
of elements.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
8/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 8 of 28
prevAll( [selector] ) Find all sibling elements in front of the current element.
siblings( [selector] )Get a set of elements containing all of the unique siblings of each of the matched set ofelements.
CSS Methods
Following table lists down all the methods which you can use to play with CSS properties:
Method Description
css( name ) Return a style property on the first matched element.
css( name, value ) Set a single style property to a value on all matched elements.
css( properties ) Set a key/value object as style properties to all matched elements.
height( val ) Set the CSS height of every matched element.
height( ) Get the current computed, pixel, height of the first matched element.
innerHeight( )Gets the inner height (excludes the border and includes the padding) for the first matchedelement.
innerWidth( )Gets the inner width (excludes the border and includes the padding) for the first matchedelement.
offset( ) Get the current offset of the first matched element, in pixels, relative to the documentoffsetParent( ) Returns a jQuery collection with the positioned parent of the first matched element.
outerHeight( [margin] )Gets the outer height (includes the border and padding by default) for the first matchedelement.
outerWidth( [margin] )Get the outer width (includes the border and padding by default) for the first matchedelement.
position( ) Gets the top and left position of an element relative to its offset parent.
scrollLeft( val )When a value is passed in, the scroll left offset is set to that value on all matched
elements.
scrollLeft( ) Gets the scroll left offset of the first matched element.
scrollTop( val )When a value is passed in, the scroll top offset is set to that value on all matchedelements.
scrollTop( ) Gets the scroll top offset of the first matched element.
width( val ) Set the CSS width of every matched element.width( ) Get the current computed, pixel, width of the first matched element.
DOM Manipulation Methods
Following table lists down all the methods which you can use to manipulate DOM elements:
Method Description
after( content ) Insert content after each of the matched elements.
append( content ) Append content to the inside of every matched element.
appendTo( selector ) Append all of the matched elements to another, specified, set of elements.
before( content ) Insert content before each of the matched elements.
clone( bool ) Clone matched DOM Elements, and all their event handlers, and select the clones.clone( ) Clone matched DOM Elements and select the clones.
empty( ) Remove all child nodes from the set of matched elements.
html( val ) Set the html contents of every matched element.
html( ) Get the html contents (innerHTML) of the first matched element.
insertAfter( selector ) Insert all of the matched elements after another, specified, set of elements.
insertBefore( selector ) Insert all of the matched elements before another, specified, set of elements.
prepend( content ) Prepend content to the inside of every matched element.
prependTo( selector ) Prepend all of the matched elements to another, specified, set of elements.
remove( expr ) Removes all matched elements from the DOM.
replaceAll( selector ) Replaces the elements matched by the specified selector with the matched elements.
replaceWith( content ) Replaces all matched elements with the specified HTML or DOM elements.
text( val ) Set the text contents of all matched elements.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
9/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 9 of 28
text( ) Get the combined text contents of all matched elements.
wrap( elem ) Wrap each matched element with the specified element.
wrap( html ) Wrap each matched element with the specified HTML content.
wrapAll( elem ) Wrap all the elements in the matched set into a single wrapper element.
wrapAll( html ) Wrap all the elements in the matched set into a single wrapper element.
wrapInner( elem )Wrap the inner child contents of each matched element (including text nodes) with a DOM
element.
wrapInner( html )Wrap the inner child contents of each matched element (including text nodes) with anHTML structure.
Event Handling
The following are cross platform and recommended event types which you can bind using JQuery:
Event Type Description
blur Occurs when the element loses focus
change Occurs when the element changes
click Occurs when a mouse click
dblclick Occurs when a mouse double-clickerror Occurs when there is an error in loading or unloading etc.
focus Occurs when the element gets focus
keydown Occurs when key is pressed
keypress Occurs when key is pressed and released
keyup Occurs when key is released
load Occurs when document is loaded
mousedown Occurs when mouse button is pressed
mouseenter Occurs when mouse enters in an element region
mouseleave Occurs when mouse leaves an element region
mousemove Occurs when mouse pointer moves
mouseout Occurs when mouse pointer moves out of an element
mouseover Occurs when mouse pointer moves over an elementmouseup Occurs when mouse button is released
resize Occurs when window is resized
scroll Occurs when window is scrolled
select Occurs when a text is selected
submit Occurs when form is submitted
unload Occurs when documents is unloaded
AJAX Methods
Methods and Description
jQuery.ajax( options )Load a remote page using an HTTP request.
jQuery.ajaxSetup( options )Setup global settings for AJAX requests.
jQuery.get( url, [data], [callback], [type] )Load a remote page using an HTTP GET request.
jQuery.getJSON( url, [data], [callback] )
Load JSON data using an HTTP GET request.
jQuery.getScript( url, [callback] )Loads and executes a JavaScript file using an HTTP GET request.
jQuery.post( url, [data], [callback], [type] )Load a remote page using an HTTP POST request.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
10/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 10 of 28
load( url, [data], [callback] )Load HTML from a remote file and inject it into the DOM.
serialize( )Serializes a set of input elements into a string of data.
serializeArray( )
Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to workwith.
Based on different events/stages following methods may be available
ajaxComplete( callback )Attach a function to be executed whenever an AJAX request completes.
ajaxStart( callback )Attach a function to be executed whenever an AJAX request begins and there is none already active.
ajaxError( callback )Attach a function to be executed whenever an AJAX request fails.
ajaxSend( callback )Attach a function to be executed before an AJAX request is sent.
ajaxStop( callback )Attach a function to be executed whenever all AJAX requests have ended.
ajaxSuccess( callback )Attach a function to be executed whenever an AJAX request completes successfully.
Built In Effect MethodsMethods and Description
animate( params, [duration, easing, callback] ) A function for making custom animations.
animate( params, options ) A function for making custom animations.
fadeIn( speed, [callback] )Fade in all matched elements by adjusting their opacity andfiring an optional callback after completion.
fadeOut( speed, [callback] )Fade out all matched elements by adjusting their opacity to 0,then setting display to "none" and firing an optional callbackafter completion.
fadeTo( speed, opacity, callback )Fade the opacity of all matched elements to a specified opacityand firing an optional callback after completion.
hide( ) Hides each of the set of matched elements if they are shown.
hide( speed, [callback] )Hide all matched elements using a graceful animation and firingan optional callback after completion.
show( )Displays each of the set of matched elements if they arehidden.
show( speed, [callback] )Show all matched elements using a graceful animation andfiring an optional callback after completion.
slideDown( speed, [callback] )Reveal all matched elements by adjusting their height and firing
an optional callback after completion.
slideToggle( speed, [callback] )Toggle the visibility of all matched elements by adjusting theirheight and firing an optional callback after completion.
slideUp( speed, [callback] )Hide all matched elements by adjusting their height and firingan optional callback after completion.
stop( [clearQueue, gotoEnd ])Stops all the currently running animations on all the specifiedelements.
toggle( ) Toggle displaying each of the set of matched elements
toggle( speed, [callback] )Toggle displaying each of the set of matched elements using agraceful animation and firing an optional callback aftercompletion.
toggle( switch )Toggle displaying each of the set of matched elements basedupon the switch (true shows all elements, false hides allelements).
-
8/3/2019 JQUERY Referance - Jan Zumwalt
11/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 11 of 28
jQuery.fx.off Globally disable all animations.
Additional Effects (UI Library)Methods and Description
Blind Blinds the element away or shows it by blinding it in.
Bounce Bounces the element vertically or horizontally n-timesClip Clips the element on or off, vertically or horizontally.
Drop Drops the element away or shows it by dropping it in.
Explode Explodes the element into multiple pieces.
Fold Folds the element like a piece of paper.
Highlight Highlights the background with a defined color.
Puff Scale and fade out animations create the puff effect.
Pulsate Pulsates the opacity of the element multiple times.
Scale Shrink or grow an element by a percentage factor.
Shake Shakes the element vertically or horizontally n-times.
Size Resize an element to a specified width and height.
Slide Slides the element out of the viewport.
Transfer Transfers the outline of an element to another.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
12/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 12 of 28
Using selectors and events
jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectorspassed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the
jQuery object. Both approaches can be combined.
To try some of these selectors, we select and modify the first ordered list in our starterkit.
To get started, we want to select the list itself. The list has an ID "orderedlist". In classic JavaScript, you couldselect it by using document.getElementById("orderedlist") . With jQuery, we do it like this:
$(document).ready(function() {
$("#orderedlist").addClass("red");
});
The starterkit provides a stylesheet with a class "red" that simply adds a red background. Therefore, when youreload the page in your browser, you should see that the first ordered list has a red background. The second list isnot modified.
Now lets add some more classes to the child elements of this list.$(document).ready(function() {
$("#orderedlist > li").addClass("blue");
});
This selects all child lis of the element with the id orderedlist and adds the class "blue".
Now for something a little more sophisticated: We want to add and remove the class when the user hovers the lielement, but only on the last element in the list.
$(document).ready(function() {
$("#orderedlist li:last").hover(function() {
$(this).addClass("green");
},function(){$(this).removeClass("green");
});
});
There are many other selectors similar to CSS and XPath syntax. More examples and a list of all availableexpressions can be found here.
For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. Some otherevents, like ready and hover, are provided as convenient methods for certain tasks.
You can find a complete list of all events in thejQuery Events Documentation.
With those selectors and events you can already do a lot of things, but there is more.
$(document).ready(function() {$("#orderedlist").find("li").each(function(i) {
$(this).append( " BAM! " + i );
});
});
find() allows you to further search the descendants of the already selected elements, therefore$("#orderedlist").find("li") is mostly the same as $("#orderedlist li").
each() iterates over every element and allows further processing. Most methods, like addClass(), useeach() themselves.
In this example, append() is used to append some text to it and set it as text to the end of each element.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
13/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 13 of 28
Another task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a formyou would like to reset after you submitted it successfully via AJAX.
$(document).ready(function() {
// use this to reset a single form
$("#reset").click(function() {
$("form")[0].reset();
});
});
This code selects the first form element and calls reset() on it. In case you had more than one form, you couldalso do this:
$(document).ready(function() {
// use this to reset several forms at once
$("#reset").click(function() {
$("form").each(function() {
this.reset();
});
});
});
This would select all forms within your document, iterate over them and call reset() for each. Note that in an.each() function, this refers to the actual element. Also note that, since the reset() function belongs to the
form element and not to the jQuery object, we cannot simply call $("form").reset() to reset all the forms onthe page.
An additional challenge is to select only certain elements from a group of similar or identical ones. jQueryprovides filter() and not() for this. While filter() reduces the selection to the elements that fit the filterexpression, not() does the contrary and removes all elements that fit the expression. Think of an unordered listwhere you want to select all li elements that have no ul children.
$(document).ready(function() {
$("li").not(":has(ul)").css("border", "1px solid black");});
This selects all li elements that have a ul element as a child and removes all elements from the selection.Therefore all li elements get a border, except the one that has a child ul.
The [expression] syntax is taken from XPath and can be used to filter by attributes. Maybe you want to select allanchors that have a name attribute:
$(document).ready(function() {
$("a[name]").css("background", "#eee" );
});
This adds a background color to all anchor elements with a name attribute.
More often than selecting anchors by name, you might need to select anchors by their "href" attribute. This can bea problem as browsers behave quite inconsistently when returning what they think the "href" value is (Note: Thisproblem was fixed recently in jQuery, available in any versions after 1.1.1). To match only a part of the value, wecan use the contains select "*=" instead of an equals ("="):
$(document).ready(function() {
$("a[href*='/content/gallery']").click(function() {
// do something with all links that point somewhere to /content/gallery
});
});
-
8/3/2019 JQUERY Referance - Jan Zumwalt
14/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 14 of 28
Until now, all selectors were used to select children or filter the current selection. There are situations where youneed to select the previous or next elements, known as siblings. Think of a FAQ page, where all answers arehidden first, and shown, when the question is clicked. The jQuery code for this:
$(document).ready(function() {
$('#faq').find('dd').hide().end().find('dt').click(function() {
$(this).next().slideToggle();
});
});
Here we use some chaining to reduce the code size and gain better performance, as '#faq' is only selected once.By using end(), the first find() is undone, so we can start search with the next find() at our #faq element,instead of the dd children.
Within the click handler, the function passed to the click() method, we use $(this).next() to find the next siblingstarting from the current dt. This allows us to quickly select the answer following the clicked question.
In addition to siblings, you can also select parent elements (also known as ancestors for those more familiar withXPath). Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this:
$(document).ready(function(){
$("a").hover(function(){
$(this).parents("p").addClass("highlight");
},function(){
$(this).parents("p").removeClass("highlight");
});
});
For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed.
Lets go one step back before continuing: jQuery is a lot about making code shorter and therefore easier to readand maintain. The following is a shortcut for the $(document).ready(callback) notation:
$(function() {
// code to execute when the DOM is ready
});
Applied to the Hello world! example, we end with this:
$(function() {
$("a").click(function() {
alert("Hello world!");
});
});
Now, with the basics at hand, we want to explore some other aspects, starting with AJAX.
Interesting links for this chapter:
jQuery API documentation
Visual jQuery - A categorized browsable API documentation.
jQuery Selectors
jQuery Events
jQuery DOM Traversing
Using Ajax
In this part we write a small Ajax application, that allows the user to rate something, just like it is done onyoutube.com.
We need some server code for this. My example uses a php file that reads the "rating" parameter and returns thenumber of ratings and the average rating. Have a look at rate.php for the server-side code.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
15/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 15 of 28
We don't want this example to work without Ajax, although it may be possible, we therefore generate thenecessary markup with jQuery and append it to a container div with an ID of "rating".
$(document).ready(function() {
// generate markup
$("#rating").append("Please rate: ");
for ( var i = 1; i
-
8/3/2019 JQUERY Referance - Jan Zumwalt
16/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 16 of 28
// add click handler and pass foobar!
$('a').click(function() {
handler(foobar);
});
// if you need the context of the original handler, use apply:
$('a').click(function() {
handler.apply(this, [foobar]);});
With Ajax this simple we can cover quite a lot of "Web 2.0". Now that we've looked at some basic Ajax, let's addsome simple effects and animations to the page.
Interesting links for this chapter:
jQuery Ajax Documentation
jQuery API - Contains description and examples for append and all other jQuery methods
ThickBox - A jQuery plugin that uses jQuery to enhance the famous lightbox
Using Animation EffectsSimple animations with jQuery can be achieved with show() and hide().
$(document).ready(function(){
$("a").toggle(function(){
$(".stuff").hide('slow');
},function(){
$(".stuff").show('fast');
});
});
You can create any combination of animations with animate(), eg. a slide with a fade:
$(document).ready(function(){
$("a").toggle(function(){
$(".stuff").animate({ height: 'hide', opacity: 'hide' }, 'slow');
},function(){
$(".stuff").animate({ height: 'show', opacity: 'show' }, 'slow');
});
});
Much fancier effects can be achieved with the interface plugin collection. The site provides demos anddocumentation. While Interface is at the top of jQuery's plugin list, there are lots of others. The next part showshow to use the tablesorter plugin.
Interesting links for this chapter:
jQuery Effects Documentation
Interface plugin
Using the tablesorter plugin
The tablesorter plugin allows sorting of tables on the client side. You include jQuery, and the plugin, and tell theplugin which tables you want to sort.
To try this example you need to download the tablesorter plugin and add this line to starterkit.html (below the jqueryinclude):
-
8/3/2019 JQUERY Referance - Jan Zumwalt
17/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 17 of 28
After including the plugin, you can call it like this:
$(document).ready(function(){
$("#large").tablesorter();
});
Try clicking the headers of the table and see how it is sorted ascending on first click and descending on second.The table could use some row highlighting, we can add those by passing some options:
$(document).ready(function() {
$("#large").tablesorter({
// striping looking
widgets: ['zebra']
});
});
There are more examples and documentation about the available options at the tablesorter homepage.
Most plugins can be used like this: Include the plugin file and call the plugin method on some elements, passingsome optional settings to customize the plugin.
A up-to-date list of available plugins can be found on the jQuery Plugin site.
When you are using jQuery more often, you may find it useful to package your own code as a plugin, either toreuse it for yourself or your company, or to share it with the community. The next chapter gives some hints onhow to structure a plugin.
Interesting links for this chapter:
Plugins for jQuery
Tablesorter Plugin
Writing your own plugins
Writing your own plugins for jQuery is quite easy. If you stick to the following rules, it is easy for others to integrateyour plugin, too.
Plugin Naming
Find a name for your plugin, lets call our example "foobar". Create a file named jquery.[yourpluginname].js, eg.jquery.foobar.js
Adding a Custom Method
Create one or more plugin methods by extending the jQuery object, eg.:
jQuery.fn.foobar = function() {
// do something
};
Which will then be accessible by performing:
$(...).foobar();
Default Settings:
Create default settings that can be changed by the user, eg.:
jQuery.fn.foobar = function(options) {
var settings = jQuery.extend({
value: 5, name: "pete", bar: 655
}, options);
};
-
8/3/2019 JQUERY Referance - Jan Zumwalt
18/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 18 of 28
You can then call the plugin without options, using the defaults:
$("...").foobar();
Or with some options:
$("...").foobar({ value: 123, bar: 9 });
Documentation
If you release your plugin, you should provide some examples and documentation, too. There are lots of pluginsavailable as a great reference.
Now you should have the basic idea of plugin writing. Lets use this knowledge and write one of our own.
Checkbox Plugin
Something lots of people, trying to manipulate forms with jQuery, ask for, is checking and unchecking of radiobuttons or checkboxes. They end up with code like this:
$(":checkbox").each(function() {
this.checked = true;
this.checked = false; // or, to uncheck
this.checked = !this.checked; // or, to toggle
});
Whenever you have an each in your code, you might want to rewrite that as a plugin, pretty straightforward:
jQuery.fn.check = function() {
return this.each(function() {
this.checked = true;
});
};
This plugin can now be used:$(":checkbox").check();
Now you could write plugins for both uncheck() and toggleCheck(), too. But instead we extend our plugin toaccept some options.
jQuery.fn.check = function(mode) {
// if mode is undefined, use 'on' as default
var mode = mode || 'on';
return this.each(function() {
switch(mode) {
case 'on':
this.checked = true;
break;case 'off':
this.checked = false;
break;
case 'toggle':
this.checked = !this.checked;
break;
}
});
};
By providing a default for the option, the user can omit the option or pass one of "on", "off", and "toggle", eg.:
$(":checkbox").check();
$(":checkbox").check('on');
$(":checkbox").check('off');
-
8/3/2019 JQUERY Referance - Jan Zumwalt
19/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 19 of 28
$(":checkbox").check('toggle');
Optional Settings
With more than one optional setting, this approach gets complicated, because the user must pass null values if hewants to omit the first parameter and only use the second.
The use of the tablesorter in the last chapter demonstrates the use of an object literal to solve this problem. Theuser can omit all parameters or pass an object with a key/value pair for every setting he wants to override.
For an exercise, you could try to rewrite the Voting code from the fourth section as a plugin. The plugin skeletonshould look like this:
jQuery.fn.rateMe = function(options) {
// instead of selecting a static container with
// $("#rating"), we now use the jQuery context
var container = this;
var settings = jQuery.extend({
url: "rate.php"
// put more defaults here
}, options);
// ... rest of the code ...
// if possible, return "this" to not break the chain
return this;
});
And allowing you to run the plugin like so:
$(...).rateMe({ url: "test.php" });
$(document).ready Method
The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if
all the graphics are not loaded yet$(document).ready(function() {
alert("document is ready");
});
Selectors
JQuery provides a simple way to select single element or group of elements. You can access element by type(div, span, p), id, CSS class and attribute etc. I have explained basic selectors here. you can find some otherselector in attached project with examples
JQuery Example Code Description
$('element') $('blockquote').css('color','red');it select all elements with the give tag name.
in this example it will return all
elements in the document.
$('#id') $('#item1').css('color','red');
it select single element with the give id. if
more than one element has been assignedsame id, first match result will be return.
$('.class') $('.myCss').css('color','red'); it select all the elements with given class.
Sliding Effect
JQuery provides three method to show or hide elements in sliding behavior.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
20/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 20 of 28
1. SlideDown(speed, callback): This method gradually increase the height of the elements,from hidden to visible.
2. SlideUp(speed, callback): This method gradually decrease the height of the elements,from visible to hidden.
3. SlideToggle(speed, callback): This method toggle between SildeUp() and
SlideDown() for selected elements.
All three methods has "Speed" and "callback" parameters.
Speed parameter can have following values
slow normal fast milliseconds. e.g. 100, 500, 1000 etc.
The callback parameter is the name of a function that executes after the function completes.
Sliding Example
According to your website design, decide collapsible Area and element on which you will handle Slide behavior. In
this example I created Box using DIVs and choose DIV having id contentArea for sliding.
Collapse Box (Click Here)
Close
Your text will be here
Register click event of the html element and call SlideToggle and SlidUp method for the contentArea.
The more detail of this example is available in attached project.
$(document).ready(function () {
$("#lnkCollapse").click(function () {
$("#contentArea").slideToggle("slow");
});
$("#lnkClose").click(function () {
$("#contentArea").slideUp(200);
});
});
Fade Effect
-
8/3/2019 JQUERY Referance - Jan Zumwalt
21/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 21 of 28
JQuery also provides four methods to gradually change the opacity of the selected element using Fade effect.
1. fadeTo(speed, opacity, callback): This method change the opacity of selected elementsto specified opacity.
2. fadeIn(speed, callback): This method gradually increase the opacity of the elements,from hidden to visible.
3. fadeOut(speed, callback): This method gradually decrease the opacity of the elements,from visible to hidden.
4. fadeToggle(speed, callback): This method toggle between FadeIn() and FadeOut()
for selected elements.
In this example, I will set the opacity of the image on hover. Add images in to the DIV and assign id fadeExp1 todiv.
In ready() function set the default opacity of all image using $(#fadeExp1 img).fadeTo(0, 0.3);
statement. The register Hover event on each image and provide two functions in it, one for mouse over and onefor mouse our and set the opacity of element there. See example code below
$(document).ready(function () {
$("#fadeExp1 img").fadeTo(0, 0.3);
$("#fadeExp1 img").hover(function () {
$(this).fadeTo("slow", 1.0);
},
function () {$(this).fadeTo("slow", 0.3);
}
);
});
Animation Efftect
JQuery also provides an easy way to animate element. the syntax of animate method is
.animate( properties, [duration], [easing], [complete])
1. properties: A map of CSS properties, which changes during animation.2. duration: String or number to determine the duration of the animation.3. easing: the name of easing function to use for the transition.4. complete: A function to call on the complete of animation.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
22/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 22 of 28
A very cool and simple example for the icons list in your website, simply register hover event on the image. Onmover over set top=-15 and on mouse out set top=0 again.
$("#divSocial a img").hover(
function () {
$(this).animate({ top: "-15" });
},
function () {
$(this).animate({ top: "0" });}
);
Dont forget to set the relative position of the image.
#divSocial a img
{
position: relative;
border: none;
}
Create Tab Control
You can easily create sophisticated tab control using JQuery. Let start learning how can we quickly create tabcontrol. Create Tab Header or tabs by assigning IDs to each element as I assigned tab1, tab2 and tab3. Setfirst element as selected by assigning css class selectTabHeader.
Now create Tab content area. I created separate divs for each tab content. Assign same id tab-data to contentdiv. as I assigned in given example and also assign dummy CSS class to div having same id as parent tab buttoncontains. I assign css class tab1, tab2 and tab3.
Tab 1
Tab 2
Tab 3
tab 1 data
tab 2 data
tab 3 data
-
8/3/2019 JQUERY Referance - Jan Zumwalt
23/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 23 of 28
By default Hide all tab content area using css and display only selected tab contents.
#tab-data{
display: none;
}
#tab-data.selectedTab
{
display: block;
color: black;
background: white;
height: 400px;
padding: 5px;
}
Register click event of all header buttons. On the click of element remove selectTabHeader CSS class from lastselected element and then assign selected Css class to clicked element by using command.
$('.selectTabHeader').removeClass('selectTabHeader');
$(this).addClass('selectTabHeader');
Use same technique for content area. Remove Css class selectedTab from last selected tab and assign thisclass to content area of selected element.
Simple get the id of click element. Suppose user clicked on tab2. Remove the class "selectedTab" of lastselected content using command.
var v = this.id;
$('.selectedTab').removeClass('selectedTab');
$('.' + v).addClass('selectedTab');
Now you have to show the content area of the selected element. Simply find html element which have css classsame as the id of selected element. Suppose tab2", assign "selectedTab" css class to that element.
$(document).ready(function () {
$('#tabHeader a').click(function () {
// Set header
$('.selectTabHeader').removeClass('selectTabHeader');
$(this).addClass('selectTabHeader');
// Show Actual area
var v = this.id;
$('.selectedTab').removeClass('selectedTab');
$('.' + v).addClass('selectedTab');
});
});
Create Carousel
-
8/3/2019 JQUERY Referance - Jan Zumwalt
24/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 24 of 28
After reading previous topics, now you have enough knowledge to create advance UI controls. In this example Iwill explain you to create Carousel, which will change the images in sliding style. User can also change imageusing navigation buttons and also he can directly go to image using number options. Write the HTML as givenbelow.
Here is a description of first image
Description of second image
I am going to write 3rd image.
123
-
8/3/2019 JQUERY Referance - Jan Zumwalt
25/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 25 of 28
In ready function, assign active CSS class to first element. After that determine the width of the total reel. Get thewidth of the window and then get the total number of images. Multiply the Width by size, you will get the totalwidth of the reel. Then assign this width to the imageReel Css class.
$(".paging a:first").addClass("active");
//Get size of images, number of images, Determine the size of the image reel.
var imageWidth = $(".carouselWindow").width();
var imageSum = $(".imageReel .image img").size();
var imageReelWidth = imageWidth * imageSum;
//Adjust the image reel to its new size
$(".imageReel").css({ 'width': imageReelWidth });
Image rotating method also has very simple logic. You just need to determine the left position of the Image reel.So get the index of the active image. Multiply it with image width to determine to slide distance. Then animate theleft Css property.
rotate = function () {
var triggerID = $active.attr("rel") - 1; //Get number of times to slide
var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs
to slide
$(".paging a").removeClass('active'); //Remove all active class
$active.addClass('active');
//Slider Animation
$(".imageReel").animate({
left: -image_reelPosition
}, 500);
};
startRotation() is a method which kicks off the rotation. It selects next active element after some interval
and calls rotate() to display this active image.
function startRotation() {
play = setInterval(function () {
$active = $('.paging a.active').next();
if ($active.length == 0) {
$active = $('.paging a:first'); //go back to first
}
rotate(); //Trigger the paging and slider function
}, 7000); //Timer speed in milliseconds
}
Register click event on the page number, when user will click, select it as active element and immediately slide tothat image.
$(".paging a").click(function () {
$active = $(this); //Activate the clicked paging
//Reset Timer
RotateImmediate();
returnfalse; //Prevent browser jump to link anchor
});
Slide next and previous functionality is also very simple. Get current element and find its next or previous whereyou want to navigate and after selecting call RoatateImmediate()method.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
26/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 26 of 28
function RotateNext() {
var next = $('.paging a.active').next();
if (next.length >0) {
$active = next;
RotateImmediate();
}
}
function RotatePrevious() {var next = $('.paging a.active').prev();
if (next.length >0) {
$active = next;
RotateImmediate();
}
}
Next steps
If you plan to develop more JavaScript, you should consider the Firefox extension called FireBug. It provides aconsole (nice to replace alerts), a debugger and other useful stuff for the daily JavaScript development.
-
8/3/2019 JQUERY Referance - Jan Zumwalt
27/28
NeatInfo.com by Jan Zumwalt February 10, 2012Copyright 1995-2012
Pg 27 of 28
Note:
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
-
8/3/2019 JQUERY Referance - Jan Zumwalt
28/28
Note:
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________