diff --git a/page/ajax/ajax-and-forms.md b/page/ajax/ajax-and-forms.md index efdfc695..aa81268c 100644 --- a/page/ajax/ajax-and-forms.md +++ b/page/ajax/ajax-and-forms.md @@ -10,14 +10,16 @@ Serializing form inputs in jQuery is extremely easy. Two methods come supported The `serialize` method serializes a form's data into a query string. For the element's value to be serialized, it **must** have a `name` attribute. Please noted that values from inputs with a type of `checkbox` or `radio` are included only if they are checked. - - +``` +// Turning form data into a query string $('#myForm').serialize(); // creates a query string like this: field_1=something&field2=somethingElse - + +``` While plain old serialization is great, sometimes your application would work better if you sent over an array of objects, instead of just the query string. For that, jQuery has the `serializeArray` method. It's very similar to the `serialize` method listed above, except it produces an array of objects, instead of a string. - +``` +// Creating an array of objects containing form data $('#myForm').serializeArray(); // creates a structure like this: @@ -25,7 +27,7 @@ $('#myForm').serializeArray(); // { name : 'field_1', value : 'something' }, // { name : 'field_2', value : 'somethingElse' } // ] - +``` ### Client-side validation Client-side validation is, much like many other things, extremely easy using jQuery. While there are several cases developers can test for, some of the most common ones are: presence of a required input, valid usernames/emails/phone numbers/etc..., or checking an "I agree..." box. @@ -34,7 +36,8 @@ Please note that it is advisable that you also perform server-side validation fo With that being said, let's jump on in to some examples! First, we'll see how easy it is to check if a required field doesn't have anything in it. If it doesn't, then we'll `return false`, and prevent the form from processing. - +``` +// Using validation to check for the presence of an input $("#form").submit(function( e ) { if ( $(".required").val().length === 0 ) { // if .required's value's length is zero // usually show some kind of error message here @@ -44,11 +47,12 @@ $("#form").submit(function( e ) { // run $.ajax here } }); - +``` Let's see how easy it is to check for invalid characters in a username: - +``` +// Validate a phone number field $("#form").submit(function( e ) { var inputtedPhoneNumber = $("#phone").val() , phoneNumberRegex = ^\d*$/; // match only numbers @@ -61,7 +65,7 @@ $("#form").submit(function( e ) { // run $.ajax here } }) - +``` @@ -70,19 +74,21 @@ A prefilter is a way to modify the ajax options before each request is sent (hen For example, say we would like to modify all crossDomain requests through a proxy. To do so with a prefilter is quite simple: - +``` +// Using a proxy with a prefilter $.ajaxPrefilter(function( options, originalOptions, jqXHR ) { if ( options.crossDomain ) { options.url = "http://mydomain.net/proxy/" + encodeURIComponent(options.url ); options.crossDomain = false; } }); - +``` You can pass in an optional argument before the callback function that specifies which `dataTypes` you'd like the prefilter to be applied to. For example, if we want our prefilter to only apply to `JSON` and `script` requests, we'd do: - +``` +// Using the optional dataTypes argument"> $.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) { // do all of the prefiltering here, but only for requests that indicate a dataType of "JSON" or "script" }) - +``` diff --git a/page/ajax/ajax-events.md b/page/ajax/ajax-events.md index ac7a938e..b1c432c8 100644 --- a/page/ajax/ajax-events.md +++ b/page/ajax/ajax-events.md @@ -8,8 +8,9 @@ this behavior inside every Ajax request, you can bind Ajax events to elements just like you'd bind other events. For a complete list of Ajax events, visit [ Ajax Events documentation on docs.jquery.com ]( http://docs.jquery.com/Ajax_Events ). - +``` +// Setting up a loading indicator using Ajax Events $('#loading_indicator') .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); - +``` diff --git a/page/ajax/ajax-excercises.md b/page/ajax/ajax-excercises.md index 396dfb16..5bf90dbe 100644 --- a/page/ajax/ajax-excercises.md +++ b/page/ajax/ajax-excercises.md @@ -20,11 +20,11 @@ need to leverage the href of that link to get the proper content from blog.html. Once you have the href, here's one way to process it into an ID that you can use as a selector in `$.fn.load`: - +``` var href = 'blog.html#post1'; var tempArray = href.split('#'); var id = '#' + tempArray[1]; - +``` Remember to make liberal use of `console.log` to make sure you're on the right path! diff --git a/page/ajax/jquery-ajax-methods.md b/page/ajax/jquery-ajax-methods.md index 9bd3fc7b..405a7285 100644 --- a/page/ajax/jquery-ajax-methods.md +++ b/page/ajax/jquery-ajax-methods.md @@ -23,7 +23,8 @@ documentation of the configuration options, visit [http://api.jquery.com/jQuery.ajax/](http://api.jquery.com/jQuery.ajax/ "$.ajax documentation on api.jquery.com"). - +``` +// Using the core `$.ajax` method $.ajax({ // the URL for the request url : 'post.php', @@ -58,9 +59,9 @@ $.ajax({ alert('The request is complete!'); } }); - +``` -
+
### Note A note about the dataType setting: if the server sends back data that is in a @@ -191,7 +192,7 @@ The URL for the request. Required. The data to be sent to the server. Optional. This can either be an object or a query string, such as `foo=bar&baz=bim`. -
+
### Note This option is not valid for `$.getScript`. @@ -208,13 +209,14 @@ object. The type of data you expect back from the server. Optional. -
+
### Note This option is only applicable for methods that don't already specify the data type in their name.
- +``` +// Using jQuery's Ajax convenience methods // get plain text or html $.get('/users.php', { userId : 1234 }, function(resp) { console.log(resp); @@ -231,7 +233,7 @@ $.getJSON('/details.php', function(resp) { console.log(k + ' : ' + v); }); }); - +``` ### `$.fn.load` @@ -241,12 +243,14 @@ uses the returned HTML to populate the selected element(s). In addition to providing a URL to the method, you can optionally provide a selector; jQuery will fetch only the matching content from the returned HTML. - +``` +// Using `$.fn.load` to populate an element $('#newContent').load('/foo.html'); - +``` - +``` +// Using `$.fn.load` to populate an element based on a selector $('#newContent').load('/foo.html #myDiv h1:first', function(html) { alert('Content updated!'); }); - +``` diff --git a/page/ajax/key-concepts.md b/page/ajax/key-concepts.md index 418d1cae..5a1a1711 100644 --- a/page/ajax/key-concepts.md +++ b/page/ajax/key-concepts.md @@ -46,7 +46,7 @@ For adding a new script to the page For transporting JSON-formatted data, which can include strings, arrays, and objects -
+
### Note As of jQuery 1.4, if the JSON data sent by your server isn't properly @@ -74,19 +74,19 @@ Ajax calls are asynchronous by default, the response is not immediately available. Responses can only be handled using a callback. So, for example, the following code will not work: - +``` var response; $.get('foo.php', function(r) { response = r; }); console.log(response); // undefined! - +``` Instead, we need to pass a callback function to our request; this callback will run when the request succeeds, at which point we can access the data that it returned, if any. - +``` $.get('foo.php', function(response) { console.log(response); }); - +``` ### Same-Origin Policy and JSONP diff --git a/page/ajax/working-with-jsonp.md b/page/ajax/working-with-jsonp.md index df164acb..09e5dba3 100644 --- a/page/ajax/working-with-jsonp.md +++ b/page/ajax/working-with-jsonp.md @@ -9,7 +9,8 @@ particularly great source of JSONP-formatted data is the [Yahoo! Query Language](http://developer.yahoo.com/yql/console/), which we'll use in the following example to fetch news about cats. - +``` +// Using YQL and JSONP $.ajax({ url : 'http://query.yahooapis.com/v1/public/yql', @@ -31,7 +32,7 @@ $.ajax({ console.log(response); } }); - +``` jQuery handles all the complex aspects of JSONP behind-the-scenes — all we have to do is tell jQuery the name of the JSONP callback parameter specified by YQL diff --git a/page/effects/built-in-effects.md b/page/effects/built-in-effects.md index a319f2ca..6a7352c1 100644 --- a/page/effects/built-in-effects.md +++ b/page/effects/built-in-effects.md @@ -33,9 +33,9 @@ Hide the selected elements with a vertical sliding motion. Show or hide the selected elements with a vertical sliding motion, depending on whether the elements are currently visible. - +``` +// A basic use of a built-in effect $('h1').show(); - ### Changing the Duration of Built-in Effects @@ -43,33 +43,35 @@ With the exception of `$.fn.show` and `$.fn.hide`, all of the built-in methods are animated over the course of 400ms by default. Changing the duration of an effect is simple. - +``` +// Setting the duration of an effect"> $('h1').fadeIn(300); // fade in over 300ms $('h1').fadeOut('slow'); // using a built-in speed definition - +``` ### jQuery.fx.speeds jQuery has an object at `jQuery.fx.speeds` that contains the default speed, as well as settings for "`slow`" and "`fast`". - +``` speeds: { slow: 600, fast: 200, // Default speed _default: 400 } - +``` It is possible to override or add to this object. For example, you may want to change the default duration of effects, or you may want to create your own effects speed. - +``` +// Augmenting `jQuery.fx.speeds` with custom speed definitions"> jQuery.fx.speeds.blazing = 100; jQuery.fx.speeds.turtle = 2000; - +``` ### Doing Something when an Effect is Done @@ -82,15 +84,17 @@ conclusion of the animation. Inside of the callback function, the keyword this refers to the element that the effect was called on; as we did inside of event handler functions, we can turn it into a jQuery object via $(this). - +``` +// Running code when an animation is complete"> $('div.old').fadeOut(300, function() { $(this).remove(); }); - +``` Note that if your selection doesn't return any elements, your callback will never run! You can solve this problem by testing whether your selection returned any elements; if not, you can just run the callback immediately. - +``` +// Run a callback even if there were no elements to animate var $thing = $('#nonexistent'); var cb = function() { @@ -102,4 +106,4 @@ returned any elements; if not, you can just run the callback immediately. } else { cb(); } - +``` diff --git a/page/effects/custom-effects.md b/page/effects/custom-effects.md index 717ea3ab..8468d493 100644 --- a/page/effects/custom-effects.md +++ b/page/effects/custom-effects.md @@ -6,7 +6,8 @@ jQuery makes it possible to animate arbitrary CSS properties via the `$.fn.animate` method. The `$.fn.animate` method lets you animate to a set value, or to a value relative to the current value. - +``` +// Custom effects with `$.fn.animate`"> $('div.funtimes').animate( { left : "+=50", @@ -15,9 +16,9 @@ value, or to a value relative to the current value. 300, // duration function() { console.log('done!'); // calback }); - +``` -
+
Color-related properties cannot be animated with `$.fn.animate` using jQuery out of the box. Color animations can easily be accomplished by including the [color plugin](http://github.com/jquery/jquery-color). We'll discuss using @@ -34,7 +35,8 @@ natural transitions in your animations, various easing plugins are available. As of jQuery 1.4, it is possible to do per-property easing when using the `$.fn.animate` method. - +``` +// Per-property easing"> $('div.funtimes').animate( { left : [ "+=50", "swing" ], @@ -42,7 +44,7 @@ As of jQuery 1.4, it is possible to do per-property easing when using the }, 300 ); - +``` For more details on easing options, see [Animation documentation on api.jquery.com](http://api.jquery.com/animate/). diff --git a/page/effects/managing-effects.md b/page/effects/managing-effects.md index 9743df5f..1c16a2e9 100644 --- a/page/effects/managing-effects.md +++ b/page/effects/managing-effects.md @@ -14,9 +14,9 @@ Stop currently running animations on the selected elements. Wait the specified number of milliseconds before running the next animation. - +``` $('h1').show(300).delay(1000).hide(300); - +``` ### `jQuery.fx.off` diff --git a/page/effects/queue_and_dequeue_explained.md b/page/effects/queue_and_dequeue_explained.md index 7f869d63..9e4c24da 100644 --- a/page/effects/queue_and_dequeue_explained.md +++ b/page/effects/queue_and_dequeue_explained.md @@ -9,21 +9,21 @@ When you use the animate and show, hide, slideUp, etc effect methods, you’re adding a job on to the fx queue.By default, using queue and passing a function, will add to the fx queue. So we’re creating our own bespoke animation step: - +``` $('.box').animate({ height : 20 }, 'slow') .queue(function () { $('#title').html("We're in the animation, baby!"); }); - +``` As I said though, these methods come in pairs, so anything you add using queue, you need to dequeue to allow the process to continue. In the code above, if I chained more animations on, until I call $(this).dequeue(), the subsequent animations wouldn’t run: - +``` $('.box').animate({ height : 20 }, 'slow') @@ -34,14 +34,14 @@ $('.box').animate({ .animate({ height: 150 }); - +``` Keeping in mind that the animation won’t continue until we’ve explicitly called dequeue, we can easily create a pausing plugin, by adding a step in the queue that sets a timer and triggers after n milliseconds, at which time, it dequeues the element: - +``` $.fn.pause = function (n) { return this.queue(function () { var el = this; @@ -58,7 +58,7 @@ $('.box').animate({ .animate({ height: 150 }); - +``` Remember that the first argument for queue and dequeue are `fx`, and that in all of these examples I’m not including it because jQuery set the argument to diff --git a/page/effects/uses_of_queue_and_dequeue.md b/page/effects/uses_of_queue_and_dequeue.md index ce19eab9..07f5f467 100644 --- a/page/effects/uses_of_queue_and_dequeue.md +++ b/page/effects/uses_of_queue_and_dequeue.md @@ -16,7 +16,7 @@ To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I’ve seen is `.delay()`: - +``` $.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; @@ -28,7 +28,7 @@ $.fn.delay = function( time, type ) { }, time ); }); }; - +``` ## The default queue – fx @@ -44,7 +44,7 @@ properties that are not shared with other queues. - It’s the default! The fx queue is used by `.animate()` and all functions that call it by default. -
+
If you are using a custom queue, you must manually `.dequeue()` the functions, they will not auto start!
@@ -58,7 +58,7 @@ function. ## Quick Examples: - +``` // lets assume $elem is a jQuery object that points to some element we are animating. var queue = $elem.queue(); // remove the last function from the animation queue. @@ -67,11 +67,11 @@ var lastFunc = queue.pop(); queue.unshift(lastFunc); // replace queue with the first three items in the queue $elem.queue(queue.slice(0,3)); - +``` ### An animation (fx) queue example: - +``` $(function() { // lets do something with google maps: var $map = $("#map_canvas"); @@ -119,11 +119,11 @@ $(function() { marginTop: 0 }, resized); }); - +``` ### Queueing something like Ajax Calls: - +``` // jQuery on an empty object, we are going to use this as our Queue var ajaxQueue = $({}); @@ -161,11 +161,11 @@ $("#items li").each(function(idx) { } }); }); - +``` ### Another custom queue example - +``` var theQueue = $({}); // jQuery on an empty object - a perfect queue holder $.each([1,2,3],function(i, num) { @@ -193,4 +193,4 @@ $("