Reputation: 320
I want to use jQuery to achieve multiple effects. When an user click on an element, this calls a set of functions inside that click handler. Is there a way in jQuery to have a delay between each action executing in the function?
Example would be:
$(function() {
$('.activator').on('click', function() {
$(this).toggleClass('animated');
$('.app').css('background',$(this).css('background'));
});
})
Instead of having the activator element perform the animation it receives from the class, and then the app receiving the background, they both happen at the same time and the animation can't even be seen. How can one set a delay between the two, or multiple?
Thanks!
Upvotes: 0
Views: 191
Reputation: 42736
If it's a CSS animation then you need to set an event for animationend / transitionend
$('.activator').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',function(){
$('.app').css('background',$(this).css('background'));
});
$('.activator').on('click', function() {
$(this).toggleClass('animated');
});
Demo
$('.activator').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
$('.app').css('background', $(this).css('background'));
});
$('.activator').on('click', function() {
$(this).toggleClass('animated');
});
.activator {
transition: all 1s;
width: 200px;
height: 50px;
background: red;
}
.activator.animated {
height: 500px;
}
.app {
width: 32px;
height: 32px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="app"></div>
<div class="activator">Click me</div>
If it is a jQuery animation you would use one of the callback options, like complete
, or pass a callback function as the last argument.
jQuery("div").animate({width:"500"},{
complete:function(){
$('.app').css('background', $(this).css('background'));
}
});
//Or
jQuery("div").animate({width:"500"},function(){
$('.app').css('background', $(this).css('background'));
});
Upvotes: 4
Reputation: 11
Have you tried using .delay() before the animation?
$(this).delay(500).toggleClass('animated');
Upvotes: -1
Reputation: 19764
There's JavaScript built-in function setTimeout()
for delaying an action.
Upvotes: 1