Descrição: this is a wonderful piece of shit, enjoy! ti les more! javascript jquery, scipting! anevase vathmo gamoto!
Ejercicios de JQuery resueltos, establecidos por nivel de dificultad de menor a mayor
this is a wonderful piece of shit, enjoy! ti les more! javascript jquery, scipting! anevase vathmo gamoto!
Deskripsi lengkap
Descripción: Chuleta para imprimir y tener mano con un buen resumen de los selectores de CSS y JQuery. Están distinguidos con un puntito de color los que funcionan en cada uno o en ambos. ¡Esperamos que te sea...
Ejercicios de JQuery resueltos, establecidos por nivel de dificultad de menor a mayorDescripción completa
Workshop tradesDescripción completa
JQUERY WORKSHOP
Zubin K ,SCJP, MCSD,PMP,PGDBA, ITILv3
TRAINING EXPECTATIONS
•
Name
•
Experience in Jquery
•
Expectations from Training
2
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
3
Introduction to Java Script DOM and Objects Overview JQuery introduction Basic Jquery functions Selectors Util functions
4
Introduction to AJAX AJAX with Jquery using XML Jquery Animation JQGrid Forms Plugin
5
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.
7
this will be the ID we use to locate the object that represents this paragraph
This is the best paragraph in the document!
<SCRIPT> b = document.getElementById("bestparagraph"); b.innerHTML="Hi world!";
Told you so
dom1.html
innerHTML is an attribute of an object that corresponds to an HTML tag. It’s value is the stuff between the start tag and the end tag.
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”);
You must use unique names!
9
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
DOM also supports collections of objects, in Javascript these collections are represented as
arrays of objects.
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.writeln("Here are the images found: \n"); document.write(txt);
Add this to the bottom of any HTML document
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
Style properties can be accessed through the DOM. and can be changed in response to user generated events.
document.body.style.backgroundColor="blue"; for (i=0;i
15
You can also mess with CSS position properties
A title
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; }
Sample Document
You have been here 0 seconds.
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
clientX, clientY : coordinates of the
mouse.
currentTarget: the object that caused the
event (not supported by IE). type: the name of the event timeStamp
eventobject.html 24
onMouseOver,onMouseOut mouse moves over or leaves an element.
onHelp user asks for help (F1 or browser help button).
onKeyDown, onKeyUp, onKeyPress keyboard events
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: <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 aren’t 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;
To access the nested property, we write var ownerName = ride.owner.name;
More compact and easier to visually scan.
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 constructor—in this case Function—and 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'); }
Let’s consider the following code: function hello() { alert('Hi there!'); } setTimeout(hello,5000);
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.
Object with Functions
Object with Functions
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.
What’s the problem with JavaScript?
JavaScript was a initially introduced in Netscape 2.0B3 in Dec 1995, a.k.a. Mocha, LiveScript, Jscript, however, it’s official name is ECMAScript
JavaScript is a C-family, world’s 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.
The world’s most misunderstood programming language.
(Douglas Crockford)
Browser DOM really sucks, and this is where jQuery comes to rescue.
Introduction to jQuery
A Quality of Life by jQuery: $(“#firstName”).text(“Joe Black”); $(“button”).click(function() {alert “Clicked”;}); $(“.content”).hide(); $(“#main”).load(“content.htm”); $(“”).html(“Loading…”).appendTo(“#content”);
Very compact and fluent programming model
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
Download the latest version from http://jquery.com
$("p a") retrieve the group of links nested inside a
element
$("div.notLongForThisWorld").fadeOut(); fade out all
elements with the CSS class notLongForThisWorld
Selects document elements (more in a moment…)
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
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
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 window’s onload technique allows for only a single function
The Magic $() function $(function(){…}); Fired when the document is ready for programming. Better use the full syntax: $(document).ready(function(){…});
The full name of $() function is
jQuery(“div”);
It may be used in case of conflict with other frameworks.
The library is designed to be isolated (function(){ var jQuery=window.jQuery=window.$=function(){ // … }; })();
jQuery uses closures for isolation
Avoid $() conflict with other frameworks
var foo = jQuery.noConflict(); // now foo() is the jQuery main function foo(“div”).hide();
// remove the conflicting $ and jQuery var foo = jQuery.noConflict(true);
jQuery’s programming philosophy is: GET >> ACT $(“div”).hide() $(“”).appendTo(“body”) $(“:button”).click()
Almost every function returns jQuery, which provides a fluent programming interface and chainability: $(“div”).show() .addClass(“main”) .html(“Hello jQuery”);
Selector that resulted in single matched elements,
$("#someElement").html("I have added some text to an element"); or $("#someElement")[0].innerHTML = "I have added some text to an element";
Selector that resulted in multiple matched elements,
$("div.fillMeIn“).html("I have added some text to a group of nodes"); Is Same as var elements = $("div.fillMeIn"); for(i=0;i
$("p:even"); This selector selects all even
elements.
$("tr:nth-child(1)"); This selector selects the first row of each table.
$("body > div"); This selector selects direct
children of .
Three Major Concepts of jQuery
The $() function
Get > Act
Chainability
jQuery Selectors
All Selector
$(“*”)
// find everything
Selectors return a pseudo-array of jQuery elements
Basic Selectors By Tag:
$(“div”) //
Hello jQuery
By ID:
$(“#usr”) // John
By Class:
$(“.menu”) //
Home
Yes, jQuery implements CSS Selectors!
More Precise Selectors
$(“div.main”)
// tag and class
$(“table#data”) // tag and id
Combination of Selectors // find by id + by class $(“#content, .menu”) // multiple combination $(“h1, h2, h3, div.content”)
Hierarchy Selectors $(“table td”)
// descendants
$(“tr > td”)
// children
$(“label + input”)
// next
$(“#content ~ div”)
// siblings
Selection Index Filters $(“tr:first”)
// first element
$(“tr:last”)
// last element
$(“tr:lt(2)”)
// index less than
$(“tr:gt(2)”)
// index gr. than
$(“tr:eq(2)”)
// index equals
Visibility Filters
$(“div:visible”) // if visible $(“div:hidden”) // if not
Attribute Filters $(“div[id]”)
// has attribute
$(“div[dir=‘rtl’]”)
// equals to
$(“div[id^=‘main’]”)
// starts with
$(“div[id$=‘name’]”)
// ends with
$(“a[href*=‘msdn’]”)
// contains
Forms Selectors $(“input:checkbox”)
// checkboxes
$(“input:radio”)
// radio buttons
$(“:button”)
// buttons
$(“:text”)
// text inputs
Forms Filters $(“input:checked”)
// checked
$(“input:selected”)
// selected
$(“input:enabled”)
// enabled
$(“input:disabled”)
// disabled
Find Dropdown Selected Item
$(“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
$(“
Hello
“) Generates HTML ready to be added
A Selector returns a pseudo array of jQuery objects
$(“div”).length $(“div”).size()
Returns number of selected elements. It is the best way to check selector.
Getting a specific DOM element
$(“div”).get(2) or $(“div”)[2]
Returns a 2nd DOM element of the selection
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.
Getting a specific jQuery element
$(“div”).eq(2)
Returns a 2nd jQuery element of the selection
Adding Element
$('img[alt]').add(“
Hi
”)
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
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(){
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 it’s 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.
each(fn) traverses every selected element calling fn() var sum = 0; $(“div.number”).each( function(){ sum += (+this.innerHTML); });
this – is a current DOM element
each(fn) also passes an indexer
$(“table tr”).each( function(i){ if (i % 2) $(this).addClass(“odd”); });
$(this) – convert DOM to jQuery i - index of the current element
each(fn) traverses every selected element calling fn() var anArray = ['one','two','three']; $.each(anArray,function(n,value) { //do something here }); var anObject = {one:1, two:2, three:3}; $.each(anObject,function(name,value) { //do something here }); this – is a current DOM element
Traversing HTML .next(expression)
// next sibling
.prev(expression)// previous sibling .siblings(expression)// siblings .children(expression) // children .parent(expression)
// parent
Traversing HTML - Examples
// Change CSS to odd for all the even cells in Table $('table tr').each(function (i){ if(i%2) $(this).children(':even') .addClass("odd"); } );
Check for expression $(“table td”).each(function() { if ($(this).is(“:first-child”)) { $(this).addClass(“firstCol”); } });
$.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 isn’t 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 that’s 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 .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
Getting and Setting Inner Content
$(“p”).html(“
Hello $!
”);
// escape the content of div.b $(“div.a”).text($(“div.b”).html());
Getting and Setting Values // get the value of the checked checkbox $(“input:checkbox:checked”).val(); // set the value of the textbox $(“:text[name=‘txt’]”).val(“Hello”); // select or check lists or checkboxes $(“#lst”).val([“NY”,”IL”,”NS”]);
Handling CSS Classes // add and remove class $(“p”).removeClass(“blue”).addClass(“red”);
// add if absent, remove otherwise $(“div”).toggleClass(“main”);
// test for class existance if ($(“div”).hasClass(“main”)) { //… }
Inserting new Elements // select > append to the end $(“h1”).append(“
Hello $!
”); // select > append to the beginning $(“ul”).prepend(“
Hello $!
”);
// create > append/prepend to selector $(“”).html(“9”).appendTo(“ul”); $(“”).html(“1”).prependTo(“ul”);
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 location—performing 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 targets—a copy operation.
Replacing Elements // select > replace $(“h1”).replaceWith(“
Hello
”);
// create > replace selection $(“
Hello
”).replaceAll(“h1”);
Replacing Elements while keeping the content $(“h3”).each(function(){ $(this).replaceWith(“
” + $(this).html() + ”
”); });
Deleting Elements // remove all children $(“#mainContent”).empty();
// remove selection $(“span.names”).remove(); // change position $(“p”).remove(“:not(.red)”) .appendTo(“#main”);
// 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
The default unit is Pixel (px)
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
Request – Response Paradigm User has to wait for response. Network Latency, amount of business logic involved
etc., will impact performance Performance tuning matters! Special care and effort involved in building high responsive application
“Click, wait, and refresh” user interaction Page refreshes from the server needed for all events,
data submissions, and navigation
Page-driven: Workflow is based on pages Page-navigation logic is determined by the server 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
Things happen naturally No need to click a button or a link to trigger an
event Private and Confidential
Oh! I lost Track!! What
Endless Wait !!!
a poor site! So Many hyperlinks to click to complete small piece of business Can there be any magic to change it to better user experience??
Oh!! It is boring. Even for small change, the entire page is refreshing!!!!
I spend most time in web applications
Thanks! Now AJAX came to rescue
Dull Web Experience
AJAX Private and Confidential
Interesting browsing experience
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 application’s 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.
Private and Confidential
Ajax (Asynchronous JavaScript + XML) A term coined by coined by Jesse James Garrett of Adaptive Path. Some parts of Ajax have been previously described as Dynamic HTML and
remote scripting.
What is AJAX? Ajax isn’t a technology. It’s 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
Private and Confidential
within a browser, there is AJAX engine
Private and Confidential
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
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 user’s behalf. The Ajax engine allows the user’s 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.
Private and Confidential
Private and Confidential
Real-time server-side input form data validation User IDs, serial numbers, postal codes Removes the need to have validation logic at both
client side for user responsiveness and at server side for security and other reasons
Auto-completion Email address, name, or city name may be auto-
completed as the user types
Master detail operation Based on a user selection, more detailed information
can be fetched and displayed Private and Confidential
Advanced GUI widgets and controls Controls such as tree controls, menus, and progress
bars may be provided that do not require page refreshes
Refreshing data HTML pages may poll data from a server for up-to-
date data such as scores, stock quotes, weather, or application-specific data
Simulating server side notification An HTML page may simulate a server-side
notification by polling the server in the background
Partial Submit of data. Private and Confidential
<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!"); }
}
Private and Confidential
XMLHttpRequest object’s 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;
▪ Pass true for asynchronous and false for synchronous.
XMLHttpRequest’s send method is used to send the data. XMLHttpRequest’s 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 = "" + str + "";; } function SayHello(){ var usr=window.document.f1.username.value; var url="sayhello.php?”usr="+usr; postRequest(url); } 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
Description
0
Uninitialized Open() – not called yet
1
Loading
Open() executed
2
Loaded
Send() executed
3
Interactive
Server returned chunk of data
4
Complete
Request is complete and server finihed data
Private and Confidential
Private and Confidential
Private and Confidential
Private and Confidential
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
Make navigation easy ▪ Provide links to portions of the page that are dynamically updated. If the site relies on the update of several areas of the page at different frequencies, provide a way to quickly navigate to each section. This set of links should be easily reached from the top or bottom of the page to make navigation to them quick and easily repeatable.
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
▪ Have Javascript and CSS in external file and link them
inspect the readyState or status fields of the object in the callback Document output, parameters, and dependencies
Private and Confidential
The Browser Was Never Meant For Ajax Ajax pushes the browser nearly beyond its limits without powerful 3rd party development tools, designing clean
Javascript software of any size requires some genuine discipline and effort. Ajax debugging applications in multiple browsers is difficult
Ajax Is More Involved Than Traditional Web Design and Development.
The loss of HTML user interface conventions almost limitless potential for hidden or latent functionality programmatic creation of page elements instead of declarative
Testing AJAX applications are difficult due to its asynchronous nature. Private and Confidential
What to do if XMLHttpRequest is not available? Usability concerns User might not understand that the browser has submitted the request in
background. Usual feedback mechanisms of the hourglass cursor and spinning browser "throbber" do not apply for XMLHttpRequests
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.
Dealing with asynchrony It's very important to understand that there is no guarantee that
XMLHttpRequests will complete in the order they were dispatched. Indeed, you should assume that they will not and design your application with this in mind . This requires extra precautions to be taken
AJAX brings more security threats than the traditional Web application Private and Confidential
Client Side JavaScript Library DOJO Prototype
RMI Like Remoting via Proxy DWR
AJAX Wrapper JMAKI (MAKI means Wrap in Japanese)
Java to Javascript / HTML translator GWT
MVC Server Side Scripting Phobos
Web Application framework with AJAX Extension Shale Private and Confidential
1. The technology used for Processing response A. CSS B. DOM C. XMLHttpRequest D. HTML E. Javascript Private and Confidential
2. Technology used for sending request asynchronously A. CSS B. DOM C. XMLHttpRequest D. HTML E. Javascript Private and Confidential
3. Applications that uses AJAX A. CSS B. Google map C. ServerSide.com D. None of the above
Private and Confidential
4. Synchronous calls can also be made using AJAX A. True B. False
Private and Confidential
5. Ajax Uses Javascript to bind Ajax building blocks together A. True B. False
Private and Confidential
6. Name the method of XMLHttpObject to send data to server A. Send B. Open C. Invoke D. Post
Private and Confidential
7. How to hook the callback handler? A. Using XMLHttpRequest’s onReadyStateChanged
method. B. Using XMLHttpRequest’s readyStateChanged method. C. Using XMLHttpRequest’s hookCallbackHandler method. D. Using XMLHttpRequest’s stateChanged method. Private and Confidential
8. ReadyState value for response complete: A. 1. B. 2. C. 3. D. 4.
Private and Confidential
9. Ajax User Experience: Select true statements. A. Notification to the user that the page uses AJAX. B. Always use xmlHttpRequest.open() with false as
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:
JSON is built on two structures: A collection of name/value pairs. In various
languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
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
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.
Sending GET/POST requests $.get(url,parameters,callback,type) Initiates a GET request to the server using the specified URL with any passed parameters as the query string. Parameters url (String) The URL of the server-side resource to contact via the GET method. parameters (String|Object|Array) Specifies any data that’s to be passed as request parameters. This parameter can be a string that will be used as the query string, an object whose properties are serialized into properly encoded parameters to be passed to the request, or an array of objects whose name and value properties specify the name/value pairs. callback (Function) An optional function invoked when the request completes successfully. The response body is passed as the first parameter to this callback, interpreted according to the setting of the type parameter, and the text status is passed as the second parameter. A third parameter contains a reference to the XHR instance. type (String) Optionally specifies how the response body is to be interpreted; one of html, text, xml, json, script, or jsonp. Returns The XHR instance.
Retrieving JSON Data $.getJSON(“users.aspx”, {id:1}, function(users) { alert(users[0].name); });
Preventing Browser Default Action // use different triggering function $(“div”).triggerHandler(“click”); // prevent default action in handler function clickHandler(e) { e.preventDefault(); } // or just return false function clickHandler(e) {return false;}
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:
Showing or Hiding Element // just show $(“div”).show(); // reveal slowly, slow=600ms $(“div”).show(“slow”); // hide fast, fast=200ms $(“div”).hide(“fast”); // hide or show in 100ms $(“div”).toggle(100);
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);
Fading === changing opacity
Detecting animation completion $(“div”).hide(“slow”, function() { alert(“The DIV is hidden”); });
$(“div”).show(“fast”, function() { $(this).html(“Hello jQuery”); }); // this is a current DOM element
Every effect function has a (speed, callback) overload
”); }); }; // usage $(“#log”).printLine(“Hello”); Do not use $ in the method (at least not until next slide)
Closure to solve the $ issue (function ($) { jQuery.fn.printLine = function(s) { return $(this).each(function() { this.append(“
”+ s +“
”); }); }; })(jQuery);
One more Example (function($){ $.fn.makeItBlue = function() { return this.css('color','blue'); }; })(jQuery);
Defaults and Options It's a best practice to have default settings that can get extended (using $.extend) when the plugin is invoked. So instead of calling a plugin with a large number of arguments, you can call it with one argument which is an object literal of the settings you would like to override.
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( $ ){
var methods = { init : function( options ) { }, show : function( ) { }, };
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
Show more Widget Readonly Plugin Makeit Blue Namespace example
Do not use $ in the method (at least not until next slide)
More things to explore More Functionality on every aspect URL parameters parser Browser and features detection Data Cache Utilities Helper functions Various Plug-ins
Where to go next
jQuery web-site: http://jquery.com jQuery API: http://api.jquery.com Many many blogs jQuery in Action book:
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... });
An interpreted programming language with object oriented capabilities. Not Java!
Originally called LiveScript, changed to JavaScript as a
marketing ploy by Sun and Netscape. Can also be referred to as ECMAScript.
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 substitute for knowing JavaScript jQuery is extraordinarily useful, but you should still know
how JavaScript works and how to use it correctly. This means more than Googling a tutorial and calling yourself an expert.
A solve all There is still plenty of functionality built into JavaScript
that should be utilized! Don’t 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
Represented by both $ and jQuery To use jQuery only, use jQuery.noConflict(), for
other frameworks that use $
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.
var xml = ‘OneTwo’; $(“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.
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.