Skip to content

Added jQuery Promises with Deferred and css transitions #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,38 @@ $(document).on('visibilitychange', function (e) {
console.log('Tab is now hidden!');
}
});
```
```

### jQuery Promises with Deferred and CSS Transitions

By returning `deferred.promise()` we can chain the animation every time it's successfully finished:

```javascript
var animate = function($el, cl) {
var deferred = $.Deferred();
var transitionEnd = 'transitionend webkitTransitionEnd MSTransitionEnd';

$el.addClass(cl).on(transitionEnd, function() {
deferred.resolve($(this));
});

return deferred.promise();
};

// Usage
var p = animate($('.element'), 'moveRight').then(function($el) {
// $el is returned as an argument
return animate($el, 'moveDown');
}).then(function($el) {
return animate($el, 'moveLeft');
}).then(function($el) {
return animate($el, 'moveUp');
});

// p is also a Promise
p.then(function() {
console.log('Done with all');
});
```

Demo: http://jsbin.com/zovoni/edit?html,css,js,output
27 changes: 27 additions & 0 deletions js/jquery-promises-with-deferred-and-css-transitions/snippet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// jQuery promises with deferred and CSS transitions

var animate = function($el, cl) {
var deferred = $.Deferred();
var transitionEnd = 'transitionend webkitTransitionEnd MSTransitionEnd';

$el.addClass(cl).on(transitionEnd, function() {
deferred.resolve($(this));
});

return deferred.promise();
};

// Usage
var p = animate($('.element'), 'moveRight').then(function($el) {
// $el is returned as an argument
return animate($el, 'moveDown');
}).then(function($el) {
return animate($el, 'moveLeft');
}).then(function($el) {
return animate($el, 'moveUp');
});

// p is also a Promise
p.then(function() {
console.log('Done with all');
});