- news (347)
- links (345)
- jQuery Plugins (61)
- jQuery Code Snippets (34)
- jQuery and JavaScript (21)
- plugins (17)
- jQuery News (17)
- Uncategorized (16)
- Media (13)
- jQuery Mobile (11)
- jQuery and CSS (10)
- jQuery Utilities (9)
- jQuery and Ajax (9)
- Random jQuery Stuff (9)
- jQuery Functions (8)
- jQuery Articles (8)
- images (7)
- jQuery (7)
- jQuery Tutorials (7)
- jQuery and HTML (6)
- Javascript Libraries (6)
- jQuery and WordPress (6)
- jQuery Events (6)
- jQuery Testing (6)
- jQuery Image Scripts (5)
- APIと少しのjQueryコードでGoogle Mapの地図の色を変更する - かちびと.net
- flipCounter a jQuery plugin by BloggingSquared.ca
- D&DEPARTMENT PROJECT
- iPhoneやAndroid等のタッチデバイス向けイメージギャラリー用JSライブラリ・PhotoSwipeなかなか良いですぞ - かちびと.net
- 画像ギャラリー等、スマートフォン(iPhone / Android)用にフリック・スワイプ操作を実現するjQueryプラグインまとめ | HTML5 – CSS3 mag
- PhotoSwipe
- HTML KickStart - Ultra–Lean HTML Building Blocks for Rapid Website Production - KickStart your Website Production - 99Lime.com
- Tutorials:Zebra Striping Made Easy - jQuery JavaScript Library
- Overview
- Real Shadow: jQuery Plugin that casts photorealistic shadows
- Calling a Script when button clicked - jQuery Forum
- [JS]異なる高さのdiv要素を揃えるだけでなく、均等割付やグリッドに揃えることもできるスクリプト -jQuery.grrrid.js | コリス
- 5 Excellent jQuery Mobile Tutorials | blogfreakz.com
- Jquery.ascensor.js
- Ajax Upload; A file upload script with progress-bar, drag-and-drop.
- jqBootstapValidation by ReactiveRaven
- [5]テーブル、チャート、コード表示プラグインを活用する - みてわかる!jQuery入門:ITpro
- Comparing HTML5 Mobile Web Framework - Dzyngiri
- 20 More CSS3 Tutorials and Techniques for Creating Buttons
- A jQuery plugin to help ease the transition to responsive images | Jquery Picture
- Infragistics jQuery Controls – Impressive & Professional jQuery Toolset
- remybach/jQuery.superLabels - GitHub
- Tips and best practices to develop responsive websites | CatsWhoCode.com
- What’s new for designers, May 2012 | Webdesigner Depot
- dynamo.js
Merging jQuery Deferreds and .animate()
Editor’s Note: This article originally appeared on danheberden.com.
jQuery’s .animate() method, and the shorthand methods that use it, are fantastic tools to create animations. Creating animations that link together to achieve a particular effect, and do something specific at the end of the animation, can be a painful, messy task. Luckily, we have .queue() for mashing animations together.
But what happens when you want to bridge the gap between ajax requests and animating? When you want to queue a bunch of animations, get data from the server, and handle it all at once, without a crap-load of nested callbacks? That’s when jQuery.Deferred() puts on its cape, tightens its utility belt, and saves the day.
Disclaimer
I should note, however, that this is more-or-less giving an example of a pending feature request to add deferreds support in $.fn.animate. If the feature request is accepted and landed, it won’t show up until version 1.6 of jQuery. The principles, however, speak to jQuery’s flexibility and how to forge its multitude of great features into an even stronger tool.
While this works, its behavior isn’t consistent with that of jQuery. Namely, the new custom animate method doesn’t return ‘this’, but a Deferred object. However, that’s kind of the point of $.sub(): allowing you to copy the jQuery object and have your way with it. So, do try this at home – just don’t threaten my life if your site explodes.
The Demo
The following demo is a basic, distilled use-case for this kind of situation. Clicking the button opens a div that contains a loading message. While it’s opening, it is also querying the server for information to populate the box. Once both have finished, the loading div is hidden and the box with the retrieved data remains.
Modifying .animate()
Here is the code driving the change to .animate()
-
// create a sub of jquery (Basically, a copy we can mess with)
-
var my$ = $.sub();
-
-
// make my$ have a modified animate function
-
// from jQuery.speed, forces arguments into props and options objects
-
var options = speed && typeof speed === "object" ?
-
complete: callback || !callback && easing ||
-
jQuery.isFunction( speed ) && speed,
-
duration: speed,
-
easing: callback && easing || easing &&
-
!jQuery.isFunction(easing) && easing
-
};
-
-
// create the deferred
-
var dfd = my$.Deferred(),
-
// a copy of the complete callback
-
complete = options.complete,
-
// and the count of how many items
-
-
// make a new complete function
-
options.complete = function() {
-
// that calls the old one if it exists
-
complete && complete.call( this );
-
// and decrements count and checks if it’s 0
-
if ( !–count ) {
-
// and when it is, resolves the DFD
-
dfd.resolve();
-
}
-
};
-
-
// all the hooks have been made, call the regular animate
-
-
// return the promise that we’ll do something
-
return dfd.promise();
-
};
While the comments explain just about everything, be sure to read up on $.sub() if you haven’t already. The new animate function on my$ simulates the method signature of the function, $.fn.animate, it’s attempting to replace. In short, speed, easing, and callback are forced into an options object — the same as if the second parameter was an object.
The deferred is created, a copy of the complete callback, and the count of how many items. Why? We want to fire the resolve() function on the deferred once all of the animations have finished. The complete() callback is replaced with a wrapper function that calls the original callback and decrements and checks the count. When the count reaches zero, all items have been animated and it’s safe to fire the resolve() function.
The untouched, standard version of $.fn.animate is called with the same ‘this’, properties, and the modified options object with the new complete wrapper function.
Returned is the promise, dfd.promise(), that lets $.when() do its awesomeness.
Putting it into action
If you haven’t familiarized yourself with deferreds, I highly recommend you read Eric Hynds’ fantastic article about it.
-
// retrieves content and updates a dom element
-
// returns a promise
-
function populateBox() {
-
url: ‘your/server/url’,
-
type: "POST",
-
}
-
});
-
}
-
-
// the "Get Message" click handler
-
-
// save the button, box and loading as my$ objects
-
$box = my$(‘#box’),
-
$loading = my$(‘.loading’);
-
-
// when the functions are done
-
$.when(
-
// $box was created with my$, so it will
-
// use the custom animate function
-
populateBox()
-
// then run the 1st function on success
-
// and the second function if either fails
-
).then(
-
function() {
-
// remove loading, we’re done
-
},
-
function() {
-
// get that button back here
-
// and hide the box
-
}
-
);
-
});
Because the new animate function was created on my$, the copy of jQuery made using $.sub(), .hide(), .slideUp(), and other helper functions that use the custom .animate() function.
When the animation and ajax request both succeed, thus resolving the promise as true, the first callback function of $.then() is called. However, if one of them fails, the second will be called. You can re-run the demo (by clicking on the run button) and opt to fail the ajax request to see the second function get run. The .then() function is a handy mix of .done() and .fail(), which are useful if you want to provide multiple callbacks.
Summary
While I highly doubt this will be the solution to using deferreds with .animate(), I’m confident it’ll get the ball rolling. Too, it covers some other topics, such as $.sub(), deferreds, and wrapping functions with alternate behavior, that hopefully you found interesting.
Read the full/original article at Learning jQuery
Comments are closed.
Learn more about jQuery
I only just found out that the jQuery validation plugins has a validation rule called “remote” which can be used ...
jQuery function to check if horizontal scroll is present – hasHScrollBar() – (or vertical check below also, util function to ...
jQuery function to Set any DOM Element to Top View (bring to front) using CSS Z-Index property.
Is it possible to declare arrays in JavaScript object literal notation? Example 1 – this works with arrays Declaration: Storage ...
To get the a variables type using jQuery there is a jQuery function called .type() which returns “array”, “string”, “number”, ...
In this post you can find tutorials which explain step by step different API use cases with jQuery like Google ...
For valuable work on creation of sites you need a good comfortable editor necessarily. There are many requiring paid products ...
Today we are sharing with you a collection of awesome jQuery Camera Photo plugins. They offer a range of image ...
Back in the day, if you saw something that was animated on a website it was automatically assumed to be ...
In this post, we have compiled a list of 10 jQuery HTML5 Audio players available today, most allow native audio ...
jQuery Mobile is a powerful framework for making mobile web applications. But can we use it to convert existing desktop ...
I have jotted a quick post on a Basic JavaScript Regular Expression Example to give beginners out there a taste ...
In April 2012′s edition of Interestingly Random JavaScript, jQuery and Web Development we bring you some very cool stuff such ...
In this post we are sharing you a roundup of 10 really jQuery plugins as of today. Pretty cool plugins ...
As always expected from the jQuery community, the compilation we have for you today are some good and impressive recently ...
A collection of jQuery PNG/JPEG/GIF plugins that enables image animation, cartoon-like background, etc… let them help you design displays for ...
A collection of JavaScript/jQuery Zip/File/Compressor plugins that allows you to minify your JS code and compress your JS files ready ...
Quick jQuery code snippet on how to keep an element in view. For demo scroll down on any page on ...
Here is what I think is the best and most reliable way to load jQuery library and jQuery UI Libraries. ...
jQuery code snippet which outputs all attributes of element using the default .attr() function on any dom element(s). usage: output:
Use jQuery and the Google Maps API to create your own map application.
Super cool and easy way to get stylish tooltips with jQuery.
The right way to include the jQuery library in WordPress.
