Jquery Workshop
Jquery Workshop
TRAINING EXPECTATIONS
Use slides to present key points Case Study based approach Practical -60-% Theory 30% Encourage discussions and questions Have flexible flow to address the needs
Introduction to Java Script DOM and Objects Overview JQuery introduction Basic Jquery functions Selectors Util functions
Introduction to AJAX AJAX with Jquery using XML Jquery Animation JQGrid Forms Plugin
JavaScript access to the elements of an HTML document. An object hierarchy Provides access to elements via:
ID (ID attribute of HTML tags) Order of elements in document Order of element in collection of similar elements.
this will be the ID we use to locate the object that represents this paragraph
<P ID=bestparagraph>This is the best paragraph in the document!</P> <SCRIPT> b = document.getElementById("bestparagraph"); b.innerHTML="Hi world!"; </SCRIPT> <P>Told you so</P> innerHTML is an attribute of an object that corresponds to an HTML tag. Its value is the stuff between the start tag and the end tag.
dom1.html
If you assign an ID attribute to all your HTML tags, you can access the objects that correspond to those elements directly. The JavaScript document object supports a method that allows you to get at the object that represents an HTML tag with a specific ID.
document.getElementById(foo);
Generally you should not have JavaScript variables with the same name as an ID you use to identify an HTML element.
Some browsers automatically create an variable with the same name as an ID attribute. Some browsers don't.
10
Every HTML element has a childNodes collection. The document object has collections forms, images, and links in addition to childNodes.
11
IE supports the document.all collection, which includes an object for every element (tag) in the document.
this is not supported by the W3C DOM standard and is no longer supported by Netscape/Mozilla.
It's best to avoid using document.all, but you are likely to see it used in scripts
12
<SCRIPT> var txt=""; for (var i=0; i<document.images.length;i++) { image = document.images[i]; name = image.getAttribute("src"); txt = txt + name +"<BR>"; } document.writeln("Here are the images found:<BR>\n"); document.write(txt); </SCRIPT>
13
childNodes: just immediate descendants (so subelements are not in the collection). Each member of the collection has it's own childNodes collection! You can write a recursive function that can be used to display the structure of a document by looking through the childNodes collections.
14
15
How to access objects that correspond to elements of the document. by ID, or in collections. How to know what the various object attributes are that change document element properties
need to look up the names in a DOM reference.
17
It is possible to have the browser run JavaScript programs in response to certain events:
user events (moving mouse, clicking, keypress, copy/paste, etc). document/window events (loading, unloading, resizing, scrolling, etc). form submission timed events
18
The onLoad event is triggered when an element is loaded by the browser. You can put an onLoad handler in the BODY tag:
<BODY onLoad="alert('Welcome');"> <H1>A title</H1> <P>Here is a paragraph
dom5.html
19
<SCRIPT> function start() { window.setInterval("updateTime()",1000); } var seconds=0; function updateTime() { seconds++; document.getElementById("time").innerHTML = seconds; } </SCRIPT> <BODY onLoad="start();"> <H1>Sample Document</H1> <H3>You have been here <B ID=time>0</B> seconds.</H3>
20
Schedules the JavaScript program prog to run at a time delay ms. in the future and at regular intervals after that. prog must be a string (that contains JavaScript code). You can stop the code from running with the help of window.clearInterval()
21
The onMouseMove event is triggered whenever the mouse is moving. Can get at the x,y position using the event object. Here is the example that uses this event to display current mouse coordinates when over a specific element of the document: mousemove.html
22
Whenever an event causes JavaScript code to run, an object named event is created. You can find out about the event using this object.
the previous example used clientX and clientY.
23
mouse.
currentTarget: the object that caused the
eventobject.html
24
onMouseOver,onMouseOut
mouse moves over or leaves an element.
onHelp
user asks for help (F1 or browser help button).
onUnLoad
element (could be the document) is unloaded (closed).
25
You can use the DOM to get the value of a form field, or to set the value of a form field. Assign an ID to each form field.
use the value attribute to access the current value.
26
Name: <INPUT ID=nfield TYPE=TEXT><BR> <INPUT TYPE=BUTTON VALUE="Check" onClick="validate();"> <SCRIPT> function validate() { fld = document.getElementById("nfield"); if (fld.value != "Dave") { alert("The name you typed is wrong"); fld.value="Dave"; } }
formexample.html
27
new object comes into existence via the new operator paired with the Object constructor. Creating an object is as easy as var shinyAndNew = new Object(); Properties of objects Like their server-side counterparts, JavaScript objects can contain data and possess methods
Unlike those server-side brethren, these elements arent pre-declared for an object; we create them dynamically as needed. Take a look at the following code fragment:
var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005,3,12)
When referencing properties, we can chain references to properties of objects serving as the properties of a parent object
var owner = new Object(); owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner;
This notation, which has come to be termed JSON (JavaScript Object Notation1),
A JavaScript object is an unordered collection of properties. Properties consist of a name and a value. Objects can be declared using object literals. Top-level variables are properties of window.
Functions in JavaScript are considered objects like any of the other object types that are defined in JavaScript, such as Strings, Numbers, or Dates. Like other objects, functions are defined by a JavaScript constructorin this case Functionand can be Assigned to variables Assigned as a property of an object Passed as a parameter Returned as a function result Created using literals
Defining function
function doSomethingWonderful() { alert('does something wonderful'); } doSomethingWonderful = function() { alert('does something wonderful'); }
When the timer expires, the hello function is called. Because the setTimeout() method makes a call back to a function in our own code, that function is termed a callback function.
closure is a Function instance coupled with the local variables from its environment that are necessary for its execution When a function is declared, it has the ability to reference any variables that are in its scope at the point of declaration. These variables are carried along with the function even after the point of declaration has gone out of scope, closing the declaration.
closure is a Function instance coupled with the local variables from its environment that are necessary for its execution When a function is declared, it has the ability to reference any variables that are in its scope at the point of declaration. These variables are carried along with the function even after the point of declaration has gone out of scope, closing the declaration.
Adding dynamic rows to a form on click of Button Selecting value from select and moving it to hidden field.
JavaScript was a initially introduced in Netscape 2.0B3 in Dec 1995, a.k.a. Mocha, LiveScript, Jscript, however, its official name is ECMAScript
JavaScript is a C-family, worlds worst named, extremely powerful language (not a script), totally unrelated to Java
JavaScript is a weakly typed, classless, prototype based OO language, that can also be used outside the browser. It is not a browser DOM.
(Douglas Crockford)
Browser DOM really sucks, and this is where jQuery comes to rescue.
Introduction to jQuery
jQuery is a lightweight, open-source JavaScript library that simplifies interaction between HTML and JavaScript
It was and still being developed by John Resig from Mozilla and was first announced in January 2006
It has a great community, great documentation, tons of plugins, and it was recently adopted by Microsoft
Getting Started
<script src=jquery.js/>
///<reference path=jquery.js/>
var el = $(<div>)
$(window).width()
$(div).hide();
$("p a")
retrieve the group of links nested inside a <p> element
$("div.notLongForThisWorld").fadeOut();
fade out all <div> elements with the CSS class notLongForThisWorld
we need a way to wait until DOM elements of the page are fully loaded before those operations execute. In the zebra-striping example, the entire table must load before striping can be applied. Traditionally, the onload handler for the window instance is used for this purpose, executing statements after the entire page is fully loaded. T Syntax is typically something like
window.onload = function() { $("table tr:nth-child(even)").addClass("even"); };
we need a way to wait until DOM elements of the page are fully loaded before those operations execute. In the zebra-striping example, the entire table must load before striping can be applied. Traditionally, the onload handler for the window instance is used for this purpose, executing statements after the entire page is fully loaded. T Syntax is typically something like
window.onload = function() { $("table tr:nth-child(even)").addClass("even"); };
This causes the zebra-striping code to execute after the document is fully loaded. Unfortunately, the browser not only delays executing the onload code until after the DOM tree is created but also waits until after all images and other external resources are fully loaded and the page is displayed in the browser window. As a result, visitors can experience a delay between the time that they first see the page and the time that the onload script is executed.
A much better approach would be to wait only until the document structure is fully parsed and the browser has converted the HTML into its DOM tree form before executing the script to apply the rich behaviors
we can use this technique multiple times within the same HTML document Browser will execute all of the functions we specify in the order that they are declared within the page. In contrast, the windows onload technique allows for only a single function
jQuery(div);
var foo = jQuery.noConflict(); // now foo() is the jQuery main function foo(div).hide();
jQuerys programming philosophy is: GET >> ACT $(div).hide() $(<span/>).appendTo(body) $(:button).click()
Almost every function returns jQuery, which provides a fluent programming interface and chainability:
$(div).show() .addClass(main) .html(Hello jQuery);
$("#someElement").html("I have added some text to an element"); or $("#someElement")[0].innerHTML = "I have added some text to an element";
$("p:even"); This selector selects all even <p> elements. $("tr:nth-child(1)"); This selector selects the first row of each table. $("body > div"); This selector selects direct <div> children of <body>.
Chainability
jQuery Selectors
All Selector
$(*)
// find everything
Basic Selectors
By Tag: $(div) // <div>Hello jQuery</div> By ID: $(#usr) // <span id=usr>John</span> By Class: $(.menu) // <ul class=menu>Home</ul> Yes, jQuery implements CSS Selectors!
$(div.main)
Combination of Selectors
// find by id + by class $(#content, .menu) // multiple combination $(h1, h2, h3, div.content)
Hierarchy Selectors
$(table td) $(tr > td) $(label + input) $(#content ~ div) // descendants // children // next // siblings
Visibility Filters
Attribute Filters
$(div[id]) $(div[dir=rtl]) $(div[id^=main]) $(div[id$=name]) $(a[href*=msdn]) // has attribute // equals to // starts with // ends with // contains
Forms Selectors
$(input:checkbox) $(input:radio) $(:button) $(:text) // checkboxes // radio buttons // buttons // text inputs
Forms Filters
$(input:checked) $(input:selected) $(input:enabled) $(input:disabled) // checked // selected // enabled // disabled
$(select[name=ddl] option:selected).val()
if we want to select only enabled and checked check boxes, we could use
:checkbox:checked:enabled.
Document Traversal
Generating HTML
$(<div>Hello</div>)
Generates HTML ready to be added
$(div).length $(div).size()
$(div).get(2) or $(div)[2]
Using Index
var n = $('img').index($('img#findMe'));
ordinal index of an image with the id of findMe within the entire set of images in a page.
$(div).eq(2)
Adding Element
$('img[alt]').add(<div>Hi </div>)
Filters out elements from the wrapped set using a passed selector expression, or a filtering function. Parameters expression (String|Function) Specifies a jQuery selector used to remove all elements that do not match from the wrapped set, or a function that makes the filtering decision. This function is invoked for each element in the set, with the current element set as the function context for that invocation. Any element that returns an invocation of false is removed from the set. Returns The wrapped set.
creates a wrapped set of all <td> elements and then invokes the function passed to the filter() method for each, with the current matched elements as the this value for the invocation. The function uses a regular expression to determine if the element content matches the described pattern
$('td').filter(function(){ return this.innerHTML.match(/^\d+$/) } )
$('img').addClass('seeThrough').filter('[title*=dog]).add Class('thickBorder')
Selects all images and applies the seeThrough class to them and then reduces the set to only those image elements whose title attribute contains the string dog before applying another class named thickBorder. The result is that all the images end up semitransparent, but only the tan dog gets the thick border treatment.
$.each(container,callback) Iterates over the items in the passed container, invoking the passed callback function for each. Parameters container (Array|Object) An array whose items or an object whose properties are to be iterated over. callback (Function) A function invoked for each element in the container. If the container is an array, this callback is invoked for each array item; if its an object, the callback is invoked for each object property. The first parameter to this callback is the index of the array element or the name of the object property. The second parameter is the item or property value. The function context (this) of the invocation is also set to the value passed as the second parameter. Returns The container object.
Traversing HTML
.next(expression) // next sibling
// Change CSS to odd for all the even cells in Table $('table tr').each(function (i){ if(i%2) $(this).children(':even') .addClass("odd"); } );
$.grep(array,callback,invert) Traverses the passed array invoking the callback function for each element. The return value of the callback function determines if the value is collected into a new array returned as the value of the $.grep() function. If the invert parameter is omitted or false, a callback value of true causes the data to be collected. If invert is true, a callback value of false causes the value to be collected. The original array isnt modified.
Grep in selected
// Returns Array having value > 100 var bigNumbers = $.grep(originalArray, function(value) { return value > 100; }); OR var bigNumbers = $.grep(originalArray,'a>100');
Grep in selected
// Returns Array having value > 100 var bigNumbers = $.grep(originalArray, function(value) { return value > 100; }); OR var bigNumbers = $.grep(originalArray,'a>100');
Grep in selected
// Returns Array having Bad Zip codes var badZips = $.grep( originalArray, function(value) { return value.match(/^\d{5}(-\d{4})?$/) != null; }, true);
Find in selected
// select paragraph and then find // elements with class header inside $(p).find(.header).show();
$.map(array,callback) Iterates through the passed array, invoking the callback function for each array item and collecting the return values of the function invocations in a new array. callback (Function|String) A function whose return values are collected in the new array returned as the result of a call to the $.map() function. This function is passed two parameters: the current data value and the index of that value within the original array. A string can also be passed thats converted into the callback function.
Map Examples
//Filter only Numbers var strings = ['1','2','3','4','S','6']; var values = $.map(strings,function(value){ var result = new Number(value); return isNaN(result) ? null : result; });
Advanced Chaining
$(<li><span></span></li>) // li .find(span) // span .html(About Us) // span .andSelf() // span, li .addClass(menu) // span,li .end() // span .end() // li .appendTo(ul.main-menu);
val() Returns the value property of the first element in the matched set. When the element is a multi-select element, the returned value is an array of all selections. Parameters none Returns The fetched value or values.
127
Examples
$("#textbox1").val() // Gets value of Textbox $('[name=radioGroup]:checked').val() //Value of radio buttons which are checked var mupltipleSelection = $("#MulipleSelect").val(); //Selects value in array
HTML Manipulation
$(p).html(<div>Hello $!</div>);
The disposition of the original elements depends on the number of elements serving as the target of the append. If there is a single target, the element is removed from its original locationperforming a move operation of the original element to a new parent. In the case where there are multiple targets, the original element remains in place and copies of it are appended to each of the targetsa copy operation.
Replacing Elements
// select > replace $(h1).replaceWith(<div>Hello</div>);
Deleting Elements
// remove all children $(#mainContent).empty();
Handling attributes
$(a).attr(href,home.htm); // <a href=home.htm></a>
// set the same as the first one $(button:gt(0)).attr(disabled, $(button:eq(0)).attr(disabled)); // remove attribute - enable $(button).removeAttr(disabled)
Handling attributes
$("a[href^=http]").attr("target","_blank"); // All External Links open in New Window
CSS Manipulations
// get style $(div).css(background-color); // set style $(div).css(float, left); // set multiple style properties $(div).css({color:blue, padding: 1em margin-right: 0, marginLeft: 10px});
Dimensions
// get window height var winHeight = $(window).height(); // set element height $(#main).height(winHeight);
//.width() element //.innerWidth() .width() + padding //.outerWidth() .innerWidth() + border //.outerWidth(true) including margin
Positioning
// from the document $(div).offset().top; // from the parent element $(div).position().left; // scrolling position $(window).scrollTop();
What and Why Ajax Ajax building blocks Sample code Ajax Real time applications Ajax Usage Scenario Ajax Caveats Ajax Best Practices Ajax frameworks
Private and Confidential
Desktop Applications are known for Rich User Experience. For example SpreadSheet Application. Characteristics:
program responses intuitively and quickly program gives a user meaningful feedback's instantly
Oh!! It is boring. Even for small change, the entire page is refreshing!!!!
AJAX
Private and Confidential
More pressing need for current web applications to provide Web applications differed from their web site ancestors in that they provided an instant service to their users, not just information. Whether for business process management or personal interests, developers were forced to create new interaction paradigms as users came to expect richer functionality. Web took a bold step forward through AJAX, shattering the traditional usage model that required a full page load every time new data or a new part of the applications logic was accessed. Companies began to experiment with dynamic reloading of portions of web pages, transmitting only a small amount of data to the client, resulting in a faster, and arguably better, user experience.
What is AJAX? Ajax isnt a technology. Its really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:
standards-based presentation using XHTML and CSS; dynamic display and interaction using the Document Object Model data interchange and manipulation using XML and XSLT asynchronous data retrieval using XMLHttpRequest JavaScript binding everything together
Pros
Improved user Experience AJAX can be used instead of Refresh header to Simulate Server push using polling technique. More useful for Real-time applications Used for Caching data
Cons
Back and Forward buttons do not tie in to XmlHttpRequests, so broken History Records. Needs user to be aware that AJAX calls are executing in the background; otherwise user might hit the button many times creating duplicate requests.
Private and Confidential
An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary an Ajax engine between the user and the server. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine written in JavaScript and usually tucked away in a hidden frame. AJAX engine is responsible for both rendering the interface the user sees and communicating with the server on the users behalf. The Ajax engine allows the users interaction with the application to happen asynchronously independent of communication with the server. So NO MORE staring at a blank browser window and an hourglass icon, waiting around for the server to do something.
Auto-completion
Email address, name, or city name may be autocompleted as the user types
Refreshing data
HTML pages may poll data from a server for up-todate data such as scores, stock quotes, weather, or application-specific data
<script language="javascript" type="text/javascript"> var xRequest=null; function createXMLHttpRequest() { try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = null; } } } if (request == null) alert("Error creating request object!"); }
} </script>
XMLHttpRequest objects open method will initiate a request to the specific URL.
XMLHttpRequest.open(mode,url,asynchronous); Mode can be GET / POST Asynchronous a flag indicating whether the request to be made asynchronously or not;
XMLHttpRequests send method is used to send the data. XMLHttpRequests onreadystatechange is used to hook the callback handler to the request.
This callback handler will be called by the browser when a response is received.
Private and Confidential
function postRequest(strURL) { var xmlHttp; if (window.XMLHttpRequest) { // Mozilla, Safari, ... var xmlHttp = new XMLHttpRequest(); }else if (window.ActiveXObject) { // IE var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.open('POST', strURL, true); xmlHttp.setRequestHeader('Content-Type', 'application/x-www-formurlencoded'); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { updatepage(xmlHttp.responseText); } } xmlHttp.send(strURL); }
Private and Confidential
function updatepage(str){ document.getElementById("result").innerHTML = "<font color='red' size='5'>" + str + "</font>";; } function SayHello(){ var usr=window.document.f1.username.value; var url="sayhello.php?usr="+usr; postRequest(url); } <input value="Say Hello" type="button" onclick='JavaScript:SayHello()' name="showdate"> <div id="result" align="center"></div>
Private and Confidential
As the callback handler is hooked to onReadyStateChange, ot gets called several times during Request Response life cycle. So it is mandatory to check if the response is complete before updating the page
ReadyState Values Value State 0 1 2 3 4 Description Uninitialized Open() not called yet Loading Loaded Interactive Complete Open() executed Send() executed Server returned chunk of data Request is complete and server finihed data
Provide a statement early in the page that indicates the use of AJAX technologies and informs the user that dynamic updates will occur. Provide notification of focus shift
Do not automatically shift focus on the page when an update occurs. Changing focus without warning can be distracting for some users, especially if there is no easy mechanism to return to the previous position.
Consider the use of color or a change in font size or weight to temporarily highlight the area which has updated. Ajax applications should send and receive as little information as possible to and from the server.
Private and Confidential
Whenever possible, update existing elements with new content rather than creating and adding new high-level elements to the page. Separate Behavior from Content and Presentation
Behaviour JavaScript Content - HTML / XML Presentation CSS / XSLT
inspect the readyState or status fields of the object in the callback Document output, parameters, and dependencies
Server load
Implementing an Ajax UI in place of a regular forms-based one may dramatically increase the number of requests made to the server.
AJAX brings more security threats than the traditional Web application
Private and Confidential
AJAX Wrapper
JMAKI (MAKI means Wrap in Japanese)
method. B. Using XMLHttpRequests readyStateChanged method. C. Using XMLHttpRequests hookCallbackHandler method. D. Using XMLHttpRequests stateChanged method.
Private and Confidential
a last argument value. C. Inspect ready state or status fields of the object in the callback. D. None of the above.
Private and Confidential
JSON (JavaScript Object Notation) is a lightweight datainterchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. JSON is built on two structures:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma)..
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
value can be a string in double quotes, or a number, or true or false or null, or an object or an array
<menu id="file" value="File"> <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup> </menu>
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
var cobblers = [ {"filling": "peach", "timeToBake": 30 }, {"filling": "cherry", "timeToBake": 35 }, {"filling": "blueberry", "timeToBake": 30} ];
{ "cobblers": [ {"filling": "peach", "timeToBake": 30 }, {"filling": "cherry", "timeToBake": 35 }, {"filling": "blueberry", "timeToBake": 30} ] }
Loading content
$(div).load(content.htm); // passing parameters $(#content).load(getcontent.aspx, {id:33, type:main});
Example BootCloset1
Loading content
serialize() Creates a properly formatted and encoded query string from all successful form elements in the wrapped set, or all successful form elements of forms in the wrapped set. Parameters none Returns The formatted query string.
Loading content
serializeArray() Collects the values of all successful form controls into an array of objects containing the names and values of the controls. Parameters none Returns The array of form data.
Retrieving JS Files
$.getScript(script.js, function() { doSomeFunction(); });
Examples
GetLoad.html GetJson.html GetCities.html AjaxForm.html
Events
Fires when the document is ready for programming. Uses advanced listeners for detecting. window.onload() is a fallback.
Attach Event
// execute always $(div).bind(click, fn); // execute only once $(div).one(click, fn);
blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error
(or any custom event)
jQuery.Event object
Detaching Events
$(div).unbind(click, fn);
Events Triggering
$(div).trigger(click);
Triggers browsers event action as well. Can trigger custom events. Triggered events bubble up.
Events Helpers
// attach / trigger elem.blur(fn) / elem.blur() elem.focus(fn) / elem.focus() elem.click(fn) / elem.click() elem.change(fn) / elem.change() And many others
Preventing Bubbling
// stop bubbling, keep other handler function clickHandler(e) { e.stopPropagation(); } // stop bubbling and other handlers function clickHandler(e) { e.stopImmediatePropagation(); } // or just return false function clickHandler(e) {return false;}
Live Events
// attach live event (div).live(click, fn); // detach live event (div).die(click, fn);
Currently supported events:
click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup
Effects
Sliding Elements
$(div).slideUp(); $(div).slideDown(fast); $(div).slideToggle(1000);
Fading Elements
$(div).fadeIn(fast); $(div).fadeOut(normal); // fade to a custom opacity $(div).fadeTo (fast, 0.5);
Custom Animation
// .animate(options, duration) $(div).animate({ width: 90%, opacity: 0.5, borderWidth: 5px }, 1000);
Chaining Animation
Adding Methods
// definition jQuery.fn.printLine = function(s) { return jQuery(this).each(function() { this.append(<div>+ s +</div>); }); }; // usage $(#log).printLine(Hello);
Do not use $ in the method
(at least not until next slide)
$.fn.tooltip = function( options ) { var settings = $.extend( { 'location' : 'top', 'background-color' : 'blue' }, options); return this.each(function() {
Namespacing
Under no circumstance should a single plugin ever claim more than one namespace in the jQuery.fn object. function( $ ){ $.fn.tooltip = function( options ) { Bad }; $.fn.tooltipShow = function( ) { Bad };
Namespacing
function( $ ){
Namespacing
$.fn.tooltip = function( method ) { // Method calling logic if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' ); }
Custom Selectors
$.expr[:].test = function(o, i, m, s) { // o current object in the selection // i loop index in the stack // m meta data about your selector // s stack of all the elements // return true to include the element // return false to exclude the element };
Example
Where to go next
jQuery web-site: http://jquery.com jQuery API: http://api.jquery.com Many many blogs jQuery in Action book:
Contact me
Thank YOU!
dojo.xhrGet( { // The following URL must match that used to test the server. url: "ajax.json",
handleAs: "json",
load: function(responseObject, ioArgs) { // Prints "peach" console.dir(responseObject.cobblers[0].filling); return responseObject; } // More properties for xhrGet... });
Not simple!
Although it is loosely typed and can be used by web developers in a cookbook fashion (think image rollovers), JavaScript is a fully featured programming language with many advanced features.
When JavaScript is embedded in a web browser, it is referred to as Client Side JavaScript. Contains an extended set of functionality to interface with the web browser DOM (Document Object Model). Objects, such as window and document, and functions, like event detection and handling, are included in Client Side JavaScript.
A framework for Client Side JavaScript. Frameworks provide useful alternatives for common programming tasks, creating functionality which may not be available or cumbersome to use within a language. An open source project, maintained by a group of developers, with a very active support base and thorough, well written documentation.
A solve all
There is still plenty of functionality built into JavaScript that should be utilized! Dont turn every project into a quest to jQuery-ize the problem, use jQuery where it makes sense. Create solutions in environments where they belong.
Cross browser support and detection AJAX functions CSS functions DOM manipulation DOM transversal Attribute manipulation Event detection and handling
JavaScript animation Hundreds of plugins for pre-built user interfaces, advanced animations, form validation, etc Expandable functionality using custom plugins Small foot print
$.func(); or $(selector).func1().func2().funcN();
$ jQuery Object, can be used instead of jQuery selector Selector syntax, many different selectors allowed func Chainable, most functions return a jQuery object () Function parameters
By default, represents the jQuery object. When combined with a selector, can represent multiple DOM Elements, see next slide. Used with all jQuery functions.
$( html ) Create DOM elements on-thefly from the provided String of raw HTML. $( elems ) Wrap jQuery functionality around single or multiple DOM Elements. $( fn ) A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading.
$( expr, context ) This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements. Default context is document. Used most often for DOM transversal. Selectors will return a jQuery object, which can contain one or more elements, or contain no elements at all.
$ ( expr, context )
$(p), $(form), $(input) $(p#content), $(#content), $(.brandnew), $(p span.brandnew:first-child, #content) $(p/span), $(p/span[@class=brandnew]), $(p/span:first), $(p:first/span:even) $(input:checkbox[@checked]), $(div:visible p[a]) var xml = <d><it w=h1><nm>One</nm></it><it w=h2><nm>Two</nm></it></d>; $(d it nm:contains(One), xml), $(it[@w^=h],xml)
Attached to the jQuery object or chained off of a selector statement. Most functions return the jQuery object they were originally passed, so you can perform many actions in a single line. The same function can perform an entirely different action based on the number and type of parameters.
$(li:odd).prepend(<span>Changed</span>).css({background:red});
<ul> <li> First item </li> <li> Second item </li> <li> Third item </li> </ul> <ul> <li> <span>Changed</span> First item </li> <li> Second item </li> <li> <span>Changed</span> Third item </li> </ul> <ul> <li style=background:red;> <span>Changed</span> First item </li> <li> Second item </li> <li style=background:red;> <span>Changed</span> Third item </li> </ul>
$(div:hidden).find(.foo).empty().text(Changed).end().show();
<div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> Goodbye cruel world. </span> </div> <div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> Goodbye cruel world. </span> </div> <div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> </span> </div>
<div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> Changed </span> </div>
<div> <span class=foo> Some text </span> </div> <div style=display:none> <span> More text </span> <span class=foo> Changed </span> </div>
<div> <span class=foo> Some text </span> </div> <div style=display:block> <span> More text </span> <span class=foo> Changed </span> </div>
<div> <span class=all>Select All</span> <span class=none>Select None</span> <input name=chk1 type=checkbox/> <input name=chk2 type=checkbox/> <input name=chk3 type=checkbox/> </div> <div> <span class=all>Select All</span>
or
$(span).click( function(){ if($(this).text()==Select All)) $(this).siblings(:checkbox).attr(checked,checked); else if ($(this).attr(class)==none) $(this).siblings(:checkbox).removeAttr(checked); } );
<span class=none>Select None</span> <input name=chk4 type=checkbox/> <input name=chk5 type=checkbox/> <input name=chk6 type=checkbox/> </div>
jQuery has a series of functions which provide a common interface for AJAX, no matter what browser you are using. Most of the upper level AJAX functions have a common layout:
$.func(url[,params][,callback]), [ ] optional
url: string representing server target params: names and values to send to server callback: function executed on successful communication.
$.func(url[,params][,callback])
$.get $.getJSON $.getIfModified $.getScript $.post
$.ajax, $.ajaxSetup
async beforeSend complete contentType data dataType error global ifModified processData success timeout type url
<html> <head> <title>AJAX Demo</title> <script type=text/javascript src=jquery.js> </script> <script type=text/javascript> var cnt = 0; $(function(){ $.ajaxSettings({ error:function(){alert(Communication error!);} }); $(:button).click(function(){ var input = {in:$(:textbox).val(),count:cnt}; $.getJSON(ajax.php,input,function(json){ cnt = json.cnt; $(.cnt).text(cnt) $(.msg).text(json.out); }); }); }); </script> </head> <body> <p> Input: <input type=textbox/> <input type=button value=Send/> Output # <span class=cnt></span>: <span class=msg></span> </p> </body> </html>
<?php $output = ; switch($_REQUEST[in]) { case hello: $output = Hello back.; break; case foo: $output = Foo you, too.; break; case bar: $output = Where Andy Capp can be found.; break; case foobar: $output = This is German, right?; break; default: $output = Unrecognized string.; } $count = $_REQUEST[count]+1; echo json_encode( array( out => $output, cnt => $count ) ); exit; ?>