Theoretically speaking let's say I have 3 javascript (jquery) functions that create visual effects. If I want one of them to render after the first two have been rendered, how can I do this?
Javascript:
<script type="text/javascript">
$(function() {
var transition = 'slow';
var target1 = $('#somediv');
var target2 = $('#second_div');
var target3 = $('#third_div');
target1.delay(5000).fadeIn();
target2.delay(target2Time).fadeIn();
target3.delay(target3Time).fadeIn();
});
</script>
<script type="text/javascript">
$.fn.teletype = function(opts){
var $this = this,
defaults = {
animDelay: 50
},
settings = $.extend(defaults, opts);
$.each(settings.text, function(i, letter){
setTimeout(function(){
$this.html($this.html() + letter);
}, settings.animDelay * i);
});
};
$(function(){
$('#second_div').teletype({
animDelay: 200,
text: 'Hello, this is your classmate!'
});
});
</script>
HTML:
<div id="somediv">Some Content</div>
<div id="second_div"></div>
<div id="third_div">Some third content</div>
I've made this demo. It demonstrates how to make one animation wait for two other animations to finish:
var anim1 = $( '#elem1' ).animate({ width: 200 }, 3000 );
var anim2 = $( '#elem2' ).animate({ width: 200 }, 2000 );
$.when( anim1, anim2 ).done(function () {
$( '#elem3' ).animate({ width: 200 }, 1000 );
});
Live demo: http://jsfiddle.net/m67Ua/
You can apply the same technique for your fading requirements:
var fade1 = $( '#img1' ).fadeIn( 3000 );
var fade2 = $( '#img2' ).fadeIn( 2000 );
$.when( fade1, fade2 ).done(function () {
$( '#img3' ).fadeIn( 1000 );
});
Live demo: http://jsfiddle.net/m67Ua/1/
Just as improvement, you can pass an array of animations
var array = new Array();
array.push( $( '#img1' ).fadeIn( 3000 ));
array.push( $( '#img2' ).fadeIn( 2000 ));
And then the trick is change from array to list arguments as expected by jquery, using the apply method
$.when.apply(this, array ).done(function () {
$( '#img3' ).fadeIn( 1000 );
});
Live demo:
i needed the callbacks and the done, so check this out:
$.when(
$('#container .item')
.animate({"opacity": "0"}, 1000,
function onCallbackForEach () {
console.log('callback on element called');
})
).done( function onFinally () {
console.log('done called');
});
which gives me access to handle the elements each after their animation (eg replace an old one with them), and aditionally having a single callback to do work after all of the animations have finished...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.