You are on page 1of 28

These notes have been heavily reformatted and edited.

Some material came from the following authors, Author: Jörn Zaefferer Link: http://jquery.bassistance.de/jquery-getting-started.html Site: http://www.tutorialspoint.com

NeatInfo.com – by Jan Zumwalt

Pg 1 of 28 Copyright © 1995-2012

February 10, 2012

Blank Page

NeatInfo.com – by Jan Zumwalt

Pg 2 of 28 Copyright © 1995-2012

February 10, 2012

Table of Contents

Introduction........................................................................................................................................................ 4 Setup ............................................................................................................................................................... 4 Hello World ...................................................................................................................................................... 4 Selectors (page elements)................................................................................................................................. 5 DOM Attributes .................................................................................................................................................. 6 DOM Traversing Methods.................................................................................................................................. 7 CSS Methods ..................................................................................................................................................... 8 DOM Manipulation Methods .............................................................................................................................. 8 Event Handling .................................................................................................................................................. 9 AJAX Methods ................................................................................................................................................... 9 Built In Effect Methods .................................................................................................................................... 10 Additional Effects (UI Library) ......................................................................................................................... 11 Using selectors and events............................................................................................................................. 12 Using Ajax........................................................................................................................................................ 14 Using Animation Effects.................................................................................................................................. 16 Using the tablesorter plugin............................................................................................................................ 16 Writing your own plugins ................................................................................................................................ 17 Optional Settings ............................................................................................................................................. 19 $(document).ready Method............................................................................................................................. 19 Selectors........................................................................................................................................................ 19 Sliding Effect .................................................................................................................................................. 19 Sliding Example ............................................................................................................................................. 20 Fade Effect..................................................................................................................................................... 21 Animation Efftect ............................................................................................................................................ 21 Create Tab Control......................................................................................................................................... 22 Create Carousel ............................................................................................................................................. 24 Next steps ........................................................................................................................................................ 26

NeatInfo.com – by Jan Zumwalt

Pg 3 of 28 Copyright © 1995-2012

February 10, 2012

Introduction
JQuery is a javascript library, which has wide range of actions such as Event handling, animation, html document traversing 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 the http://docs.jquery.com/Downloading_jQuery The http://docs.jquery.com/images/c/c7/Jquery-starterkit.zip StarterKit 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.html with a browser. Hello World We start with an empty html page:
<html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> // we will add our javascript code here </script> </head> <body> <!-- we will add our HTML content here --> </body> </html>

This page just loads the jquery.js library (make sure the URL points to where you stored your copy of jquery! This example assumes that you store it in the same directory as this example file). Two comments indicate where we will expand this template with code. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to 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 <body>:
<a href="">Link</a>

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 into your custom.js file. Then, open starterkit.html in the browser and click any link. You should see a pop-up window with "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

NeatInfo.com – by Jan Zumwalt

Pg 4 of 28 Copyright © 1995-2012

February 10, 2012

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:
<a href="" onclick="alert('Hello world')">Link</a>

The difference is quite obvious: We don't need to write an onclick for every single element. We have a clean separation 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 Name #ID .Class Universal (*) Multiple Elements E, F, G Description all elements which match with the given element Name. a single element which matches with the given ID all elements which match with the given Class. all elements available in a DOM. the combined results of all the specified selectors E, F or G.

Selects Selects Selects Selects Selects

Similar to above syntax and examples, following examples would give you understanding on using different type of other 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 of specialClass. $("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass". $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass. $("p a.specialClass"): This selector matches links with a class of specialClass declared within <p> elements. $("ul li:first"): This selector gets only the first <li> element of the <ul>. $("#container p"): Selects all elements matched by <p> that are descendants of an element that has an id of container. $("li > ul"): Selects all elements matched by <ul> that are children of an element matched by <li> $("strong + em"): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>. $("p ~ ul"): Selects all elements matched by <ul> that follow a sibling element matched by <p>. $("code, em, strong"): Selects all elements matched by <code> or <em> or <strong>. $("p strong, .myclass"): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass. $(":empty"): Selects all elements that have no children. $("p:empty"): Selects all elements matched by <p> that have no children. $("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>. $("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass. $("a[@rel]"): Selects all elements matched by <a> that have a rel attribute. $("input[@name=myname]"): Selects all elements matched by <input> that have a name value exactly equal to myname. $("input[@name^=myname]"): Selects all elements matched by <input> that have a name value beginning with myname. $("a[@rel$=self]"): Selects all elements matched by <p> that have a class value ending with bar $("a[@href*=domain.com]"): Selects all elements matched by <a> that have an href value containing domain.com. $("li:even"): Selects all elements matched by <li> that have an even index value. $("tr:odd"): Selects all elements matched by <tr> that have an odd index value.

NeatInfo.com – by Jan Zumwalt

Pg 5 of 28 Copyright © 1995-2012

February 10, 2012

• • • • • • • • • • • • • • • • • • • • •

$("li:first"): Selects the first <li> element. $("li:last"): Selects the last <li> element. $("li:visible"): Selects all elements matched by <li> that are visible. $("li:hidden"): Selects all elements matched by <li> 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 <li> element $("li:eq(4)"): Selects the fifth <li> element $("li:lt(2)"): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements. $("p:lt(3)"): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements. $("li:gt(1)"): Selects all elements matched by <li> after the second one. $("p:gt(2)"): Selects all elements matched by <p> after the third one. $("div/p"): Selects all elements matched by <p> that are children of an element matched by <div>. $("div//code"): Selects all elements matched by <code>that are descendants of an element matched by <div>. $("//p//a"): Selects all elements matched by <a> that are descendants of an element matched by <p> $("li:first-child"): Selects all elements matched by <li> that are the first child of their parent. $("li:last-child"): Selects all elements matched by <li> 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 <li> that contain the text second.

DOM Attributes
Following table lists down few useful methods which you can use to manipulate attributes and properties: Methods attr( properties ) attr( key, fn ) removeAttr( name ) hasClass( class ) removeClass( class ) toggleClass( class ) html( ) html( val ) text( ) text( val ) val( ) val( val ) Description Set a key/value object as properties to all matched elements. Set a single property to a computed value, on all matched elements. Remove an attribute from each of the matched elements. Returns true if the specified class is present on at least one of the set of matched elements. Removes all or the specified class(es) from the set of matched elements. Adds the specified class if it is not present, removes the specified class if it is present. Get the html contents (innerHTML) of the first matched element. Set the html contents of every matched element. Get the combined text contents of all matched elements. Set the text contents of all matched elements. Get the input value of the first matched element. Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called 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 attribute methods in different situation:

• • • • •

$("#myID").attr("custom") : This would return value of attribute custom for the first element matching with 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 <input> elements to 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 with http:// and set its target attribute to _blank $("a").removeAttr("target") : This would remove target attribute of all the links.

NeatInfo.com – by Jan Zumwalt

Pg 6 of 28 Copyright © 1995-2012

February 10, 2012

• • • • • • • • • • • •

$("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This would modify the disabled attribute to the value "disabled" while clicking Submit button. $("p:last").hasClass("selected"): This return true if last <p> tag has associated classselected. $("p").text(): Returns string that contains the combined text contents of all matched <p> elements. $("p").text("<i>Hello World</i>"): This would set "<I>Hello World</I>" as text content of the matching <p> 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 <div> 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 <button>. $("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 box with 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 DOM elements: Selector eq( index ) filter( selector ) filter( fn ) is( selector ) map( callback ) not( selector ) slice( start, [end] ) Description Reduce the set of matched elements to a single element. Removes all elements from the set of matched elements that do not match the specified selector(s). Removes all elements from the set of matched elements that do not match the specified function. Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector. Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements). Removes elements matching the specified selector from the set of matched elements. 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 add( selector ) andSelf( ) children( [selector]) closest( selector ) contents( ) end( ) find( selector ) next( [selector] ) nextAll( [selector] ) offsetParent( ) parent( [selector] ) parents( [selector] ) prev( [selector] ) Description Adds more elements, matched by the given selector, to the set of matched elements. Add the previous selection to the current selection. Get a set of elements containing all of the unique immediate children of each of the matched set of elements. Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe. Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state . Searches for descendent elements that match the specified selectors. Get a set of elements containing the unique next siblings of each of the given set of elements. Find all sibling elements after the current element. Returns a jQuery collection with the positioned parent of the first matched element. Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements. Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element). Get a set of elements containing the unique previous siblings of each of the matched set of elements.

NeatInfo.com – by Jan Zumwalt

Pg 7 of 28 Copyright © 1995-2012

February 10, 2012

prevAll( [selector] ) siblings( [selector] )

Find all sibling elements in front of the current element. Get a set of elements containing all of the unique siblings of each of the matched set of elements.

CSS Methods
Following table lists down all the methods which you can use to play with CSS properties: Method css( name ) css( name, value ) css( properties ) height( val ) height( ) innerHeight( ) innerWidth( ) offset( ) offsetParent( ) outerHeight( [margin] ) outerWidth( [margin] ) position( ) scrollLeft( val ) scrollLeft( ) scrollTop( val ) scrollTop( ) width( val ) width( ) Description Return a style property on the first matched element. Set a single style property to a value on all matched elements. Set a key/value object as style properties to all matched elements. Set the CSS height of every matched element. Get the current computed, pixel, height of the first matched element. Gets the inner height (excludes the border and includes the padding) for the first matched element. Gets the inner width (excludes the border and includes the padding) for the first matched element. Get the current offset of the first matched element, in pixels, relative to the document Returns a jQuery collection with the positioned parent of the first matched element. Gets the outer height (includes the border and padding by default) for the first matched element. Get the outer width (includes the border and padding by default) for the first matched element. Gets the top and left position of an element relative to its offset parent. When a value is passed in, the scroll left offset is set to that value on all matched elements. Gets the scroll left offset of the first matched element. When a value is passed in, the scroll top offset is set to that value on all matched elements. Gets the scroll top offset of the first matched element. Set the CSS width of every matched element. 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 after( content ) append( content ) appendTo( selector ) before( content ) clone( bool ) clone( ) empty( ) html( val ) html( ) insertAfter( selector ) insertBefore( selector ) prepend( content ) prependTo( selector ) remove( expr ) replaceAll( selector ) replaceWith( content ) text( val ) Description Insert content after each of the matched elements. Append content to the inside of every matched element. Append all of the matched elements to another, specified, set of elements. Insert content before each of the matched elements. Clone matched DOM Elements, and all their event handlers, and select the clones. Clone matched DOM Elements and select the clones. Remove all child nodes from the set of matched elements. Set the html contents of every matched element. Get the html contents (innerHTML) of the first matched element. Insert all of the matched elements after another, specified, set of elements. Insert all of the matched elements before another, specified, set of elements. Prepend content to the inside of every matched element. Prepend all of the matched elements to another, specified, set of elements. Removes all matched elements from the DOM. Replaces the elements matched by the specified selector with the matched elements. Replaces all matched elements with the specified HTML or DOM elements. Set the text contents of all matched elements.

NeatInfo.com – by Jan Zumwalt

Pg 8 of 28 Copyright © 1995-2012

February 10, 2012

text( ) wrap( elem ) wrap( html ) wrapAll( elem ) wrapAll( html ) wrapInner( elem ) wrapInner( html )

Get the combined text contents of all matched elements. Wrap each matched element with the specified element. Wrap each matched element with the specified HTML content. Wrap all the elements in the matched set into a single wrapper element. Wrap all the elements in the matched set into a single wrapper element. Wrap the inner child contents of each matched element (including text nodes) with a DOM element. Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.

Event Handling
The following are cross platform and recommended event types which you can bind using JQuery: Event Type blur change click dblclick error focus keydown keypress keyup load mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup resize scroll select submit unload Description the element loses focus the element changes a mouse click a mouse double-click there is an error in loading or unloading etc. the element gets focus key is pressed key is pressed and released key is released document is loaded mouse button is pressed mouse enters in an element region mouse leaves an element region mouse pointer moves mouse pointer moves out of an element mouse pointer moves over an element mouse button is released window is resized window is scrolled a text is selected form is submitted documents is unloaded

Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs Occurs

when when when when when when when when when when when when when when when when when when when when when when

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.

NeatInfo.com – by Jan Zumwalt

Pg 9 of 28 Copyright © 1995-2012

February 10, 2012

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 work with.

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 Methods
Methods and Description animate( params, [duration, easing, callback] ) A function for making custom animations. animate( params, options ) A function for making custom animations. Fade in all matched elements by adjusting their opacity and fadeIn( speed, [callback] ) firing an optional callback after completion. Fade out all matched elements by adjusting their opacity to 0, fadeOut( speed, [callback] ) then setting display to "none" and firing an optional callback after completion. Fade the opacity of all matched elements to a specified opacity fadeTo( speed, opacity, callback ) and firing an optional callback after completion. hide( ) Hides each of the set of matched elements if they are shown. Hide all matched elements using a graceful animation and firing hide( speed, [callback] ) an optional callback after completion. Displays each of the set of matched elements if they are show( ) hidden. Show all matched elements using a graceful animation and show( speed, [callback] ) firing an optional callback after completion. Reveal all matched elements by adjusting their height and firing slideDown( speed, [callback] ) an optional callback after completion. Toggle the visibility of all matched elements by adjusting their slideToggle( speed, [callback] ) height and firing an optional callback after completion. Hide all matched elements by adjusting their height and firing slideUp( speed, [callback] ) an optional callback after completion. Stops all the currently running animations on all the specified stop( [clearQueue, gotoEnd ]) elements. toggle( ) Toggle displaying each of the set of matched elements Toggle displaying each of the set of matched elements using a toggle( speed, [callback] ) graceful animation and firing an optional callback after completion. Toggle displaying each of the set of matched elements based toggle( switch ) upon the switch (true shows all elements, false hides all elements).

NeatInfo.com – by Jan Zumwalt

Pg 10 of 28 Copyright © 1995-2012

February 10, 2012

jQuery.fx.off

Globally disable all animations.

Additional Effects (UI Library)
Blind Bounce Clip Drop Explode Fold Highlight Puff Pulsate Scale Shake Size Slide Transfer Methods and Description Blinds the element away or shows it by blinding it in. Bounces the element vertically or horizontally n-times Clips the element on or off, vertically or horizontally. Drops the element away or shows it by dropping it in. Explodes the element into multiple pieces. Folds the element like a piece of paper. Highlights the background with a defined color. Scale and fade out animations create the puff effect. Pulsates the opacity of the element multiple times. Shrink or grow an element by a percentage factor. Shakes the element vertically or horizontally n-times. Resize an element to a specified width and height. Slides the element out of the viewport. Transfers the outline of an element to another.

NeatInfo.com – by Jan Zumwalt

Pg 11 of 28 Copyright © 1995-2012

February 10, 2012

Using selectors and events
jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectors passed 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 could select 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 you reload the page in your browser, you should see that the first ordered list has a red background. The second list is not 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 li element, 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 available expressions can be found here. For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. Some other events, like ready and hover, are provided as convenient methods for certain tasks. You can find a complete list of all events in the jQuery 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, $("#orderedlist").find("li") is mostly the same as $("#orderedlist li").

therefore

each() iterates over every element and allows further processing. Most methods, like addClass(), use each() themselves. In this example, append() is used to append some text to it and set it as text to the end of each element.

NeatInfo.com – by Jan Zumwalt

Pg 12 of 28 Copyright © 1995-2012

February 10, 2012

Another task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a form you 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 could also 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 on the page. An additional challenge is to select only certain elements from a group of similar or identical ones. jQuery provides filter() and not() for this. While filter() reduces the selection to the elements that fit the filter expression, not() does the contrary and removes all elements that fit the expression. Think of an unordered list where 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 all anchors 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 be a problem as browsers behave quite inconsistently when returning what they think the "href" value is (Note: This problem was fixed recently in jQuery, available in any versions after 1.1.1). To match only a part of the value, we can 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 }); });

NeatInfo.com – by Jan Zumwalt

Pg 13 of 28 Copyright © 1995-2012

February 10, 2012

Until now, all selectors were used to select children or filter the current selection. There are situations where you need to select the previous or next elements, known as siblings. Think of a FAQ page, where all answers are hidden 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 sibling starting 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 with XPath). 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 read and 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 on youtube.com. We need some server code for this. My example uses a php file that reads the "rating" parameter and returns the number of ratings and the average rating. Have a look at rate.php for the server-side code.

NeatInfo.com – by Jan Zumwalt

Pg 14 of 28 Copyright © 1995-2012

February 10, 2012

We don't want this example to work without Ajax, although it may be possible, we therefore generate the necessary 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 <= 5; i++ ) { $("#rating").append("<a href='#'>" + i + "</a> "); } // add markup to container and apply click handlers to anchors $("#rating a").click(function(e) { // stop normal link click e.preventDefault(); // send request $.post("rate.php", {rating: $(this).html()}, function(xml) { // format and output result $("#rating").html( "Thanks for rating, current average: " + $("average", xml).text() + ", number of votes: " + $("count", xml).text() ); }); }); });

This snippet generates five anchor elements and appends them to the container element with the id "rating". Afterwards, for every anchor inside the container, a click handler is added. When the anchor is clicked, a post request is send to rate.php with the content of the anchor as a parameter. The result returned as a XML is then added to the container, replacing the anchors. If you don't have a web server with PHP installed at hand, you can look at an online example. For a very nice example of a rating system that even works without JavaScript, visit softonic.de and click on "Kurz bewerten!" More documentation of the Ajax methods of jQuery can be found in the Ajax Documentation or on Visual jQuery filed under Ajax. A very common problem encountered when loading content by Ajax is this: When adding event handlers to your document that should also apply to the loaded content, you have to apply these handlers after the content is loaded. To prevent code duplication, you can delegate to a function. Example:
function addClickHandlers() { $("a.remote", this).click(function() { $("#target").load(this.href, addClickHandlers); }); } $(document).ready(addClickHandlers);

Now addClickHandlers is called once when the DOM is ready and then everytime when a user clicked a link with the class remote and the content has finished loading. Note the $("a.remote", this) query, this is passed as a context: For the document ready event, this refers to the document, and it therefore searches the entire document for anchors with class remote. When addClickHandlers is used as a callback for load(), this refers to a different element: In the example, the element with id target. This prevents that the click event is applied again and again to the same links, causing a crash eventually. Another common problem with callbacks are parameters. You have specified your callback but need to pass an extra parameter. The easiest way to achieve this is to wrap the callback inside another function:
// get some data var foobar = ...; // specify handler, it needs data as a paramter function handler(data) { //... }

NeatInfo.com – by Jan Zumwalt

Pg 15 of 28 Copyright © 1995-2012

February 10, 2012

// 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 add some simple effects and animations to the page.
Interesting links for this chapter: jQuery Ajax Documentation jQuery API ThickBox

- Contains description and examples for append and all other jQuery methods

- A jQuery plugin that uses jQuery to enhance the famous lightbox

Using Animation Effects
Simple 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 and documentation. While Interface is at the top of jQuery's plugin list, there are lots of others. The next part shows how 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 the plugin 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 jquery include):
<script src="jquery.tablesorter.js"></script>

NeatInfo.com – by Jan Zumwalt

Pg 16 of 28 Copyright © 1995-2012

February 10, 2012

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, passing some 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 to reuse it for yourself or your company, or to share it with the community. The next chapter gives some hints on how 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 integrate your 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); };

NeatInfo.com – by Jan Zumwalt

Pg 17 of 28 Copyright © 1995-2012

February 10, 2012

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 plugins available 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 radio buttons 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 to accept 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');

NeatInfo.com – by Jan Zumwalt

Pg 18 of 28 Copyright © 1995-2012

February 10, 2012

$(":checkbox").check('toggle');

Optional Settings
With more than one optional setting, this approach gets complicated, because the user must pass null values if he wants 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. The user 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 skeleton should 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 other selector in attached project with examples

JQuery $('element')

Example Code $('blockquote').css('color','red');

Description it select all elements with the give tag name. in this example it will return all <blockquote> elements in the document. it select single element with the give id. if more than one element has been assigned same id, first match result will be return. it select all the elements with given class.

$('#id') $('.class') Sliding Effect

$('#item1').css('color','red'); $('.myCss').css('color','red');

JQuery provides three method to show or hide elements in sliding behavior.

NeatInfo.com – by Jan Zumwalt

Pg 19 of 28 Copyright © 1995-2012

February 10, 2012

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.
<div class="box" style="width: 400px"> <div class="title"> Collapse Box (<a id="lnkCollapse" href="#" style="color: White; font-size: 12px; text-decoration: none;">Click Here</a>) </div> <div id="contentArea" class="content"> <div align="right"><a id="lnkClose" href="#" style="font-size: 10px;">Close</a></div> Your text will be here </div> </div>

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

NeatInfo.com – by Jan Zumwalt

Pg 20 of 28 Copyright © 1995-2012

February 10, 2012

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 elements to 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” to div.
<div id="fadeExp1"> <img src="Images/b1.jpg" width="100px" height="100px" /> <img src="Images/b2.jpg" width="100px" height="100px" /> <img src="Images/b3.jpg" width="100px" height="100px" /> </div>

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 one for 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. 2. 3. 4. properties: A map of CSS properties, which changes during animation. duration: String or number to determine the duration of the animation. easing: the name of easing function to use for the transition. complete: A function to call on the complete of animation.

NeatInfo.com – by Jan Zumwalt

Pg 21 of 28 Copyright © 1995-2012

February 10, 2012

A very cool and simple example for the icons list in your website, simply register hover event on the image. On mover 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" }); } );

Don’t 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 tab control. Create Tab Header or tabs by assigning IDs to each element as I assigned “tab1”, “tab2” and “tab3”. Set first 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 content div. as I assigned in given example and also assign dummy CSS class to div having same id as parent tab button contains. I assign css class “tab1”, “tab2” and “tab3”.
<div id="tabArea"> <div id="tabHeader"> <a id="tab1" class="tab selectTabHeader">Tab 1 </a> <a id="tab2" class="tab">Tab 2</a> <a id="tab3" class="tab">Tab 3 </a> </div> <div id="tabData"> <div id="tab-data" class="tab1 selectedTab"> tab 1 data </div> <div id="tab-data" class="tab2"> tab 2 data </div> <div id="tab-data" class="tab3"> tab 3 data </div> </div>

NeatInfo.com – by Jan Zumwalt

Pg 22 of 28 Copyright © 1995-2012

February 10, 2012

</div>

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 last selected 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 this class to content area of selected element. Simple get the id of click element. Suppose user clicked on “tab2”. Remove the class "selectedTab" of last selected 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 class same 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

NeatInfo.com – by Jan Zumwalt

Pg 23 of 28 Copyright © 1995-2012

February 10, 2012

After reading previous topics, now you have enough knowledge to create advance UI controls. In this example I will explain you to create Carousel, which will change the images in sliding style. User can also change image using navigation buttons and also he can directly go to image using number options. Write the HTML as given below.
<div class="advanceCarousel"> <div class="carouselWindow"> <div class="imageReel"> <div class="image"> <a href="#" target="_blank" > <img src="images/b1.jpg" /> </a> <div class="description"> Here is a description of first image </div> </div> <div class="image"> <a href="#" target="_blank" > <img src="images/b2.jpg" /> </a> <div class="description"> Description of second image </div> </div> <div class="image"> <a href="#" target="_blank" > <img src="images/b3.jpg" /> </a> <div class="description"> I am going to write 3rd image. </div> </div> </div> </div> <div class="paggingBar"> <div style="float: left;"> <a class="aNav" href="javascript:RotatePrevious();"><<</a> </div> <div style="float: right;"> <a class="aNav" href="javascript:RotateNext();">>></a> </div> <div class="paging"> <a href="#" rel="1">1</a> <a href="#" rel="2">2</a> <a href="#" rel="3">3</a> </div> </div> </div>

NeatInfo.com – by Jan Zumwalt

Pg 24 of 28 Copyright © 1995-2012

February 10, 2012

In ready function, assign active CSS class to first element. After that determine the width of the total reel. Get the width of the window and then get the total number of images. Multiply the Width by size, you will get the total width 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 the left 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 to that image.
$(".paging a").click(function () { $active = $(this); //Activate the clicked paging //Reset Timer RotateImmediate(); return false; //Prevent browser jump to link anchor });

Slide next and previous functionality is also very simple. Get current element and find its next or previous where you want to navigate and after selecting call RoatateImmediate() method.

NeatInfo.com – by Jan Zumwalt

Pg 25 of 28 Copyright © 1995-2012

February 10, 2012

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 a console (nice to replace alerts), a debugger and other useful stuff for the daily JavaScript development.

NeatInfo.com – by Jan Zumwalt

Pg 26 of 28 Copyright © 1995-2012

February 10, 2012

Note: ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________

NeatInfo.com – by Jan Zumwalt

Pg 27 of 28 Copyright © 1995-2012

February 10, 2012

Note: ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________ ______________________________________________________________

NeatInfo.com – by Jan Zumwalt

Pg 28 of 28 Copyright © 1995-2012

February 10, 2012