fadeIn and fadeOut not completing fast enough
I have two div's which when clicked fadeOut content and fadeIn new content. The code works fine until you repeatedly click both div's very frequently which causes both functions to fire and content to load underneath the previous content which should have faded out.
I was wondering if it is possible to disable the other div from being able to fire until the previous function has completed and vice versa.
$('#div1').click(function(event){
event.preventDefau开发者_JS百科lt();
$('#lastWeek').fadeOut(function(){
$('#thisWeek').fadeIn();
});
});
$('#div2').click(function(event){
event.preventDefault();
$('#thisWeek').fadeOut(function(){
$('#lastWeek').fadeIn();
});
});
Any help on this would be much appreciated :)
If you don't want to complicate things too much, and this is the only change to jQuery's behavior that you need, the simplest would be to introduce a state variable that both event handlers can check and modify as needed:
var whoIsAnimating = null;
$('#div1').click(function(event){
event.preventDefault();
if (whoIsAnimating != null) { // or != 'div1', or == 'div2', take your pick
return;
}
whoIsAnimating = 'div1';
$('#lastWeek').fadeOut(function(){
$('#thisWeek').fadeIn(function() {
whoIsAnimating = null;
});
});
});
$('#div2').click(function(event){
event.preventDefault();
if (whoIsAnimating != null) { // same here, depends on what you want
return;
}
whoIsAnimating = 'div2';
$('#thisWeek').fadeOut(function(){
$('#lastWeek').fadeIn(function() {
whoIsAnimating = null;
});
});
});
Usually what you do when something happens in the middle of animation that affects that object is you stop the animation and tell it to jump to the completed state. This prevents two interactions from running at the same time, but still gives the user the desired final state.
This is different than exactly what you asked for (you asked to ignore the user's click if still animating), but is generally a better way to do things so that's why I offered this alternate solution.
You can use the jQuery .stop(true, true)
method for that. In your code, you would add that like this:
$('#div1').click(function(event){
event.preventDefault();
$('#thisWeek').stop(true, true);
$('#lastWeek').stop(true, true).fadeOut(function(){
$('#thisWeek').stop(true, true).fadeIn();
});
});
$('#div2').click(function(event){
event.preventDefault();
$('#lastWeek').stop(true, true);
$('#thisWeek').stop(true, true).fadeOut(function(){
$('#lastWeek').stop(true, true).fadeIn();
});
});
So, at the point you want to start a new animation on an object, the .stop(true, true)
will clear all other animations and jump to the final state before starting the next animation. This will prevent two animations (an old one, not yet done and a new one) from running at the some time.
精彩评论