Search code examples
jqueryfadein

How to prevent fading in other divs when quickly clicking related dots?


I'm having a problem with transition between divs when clicking on dots below them. When I'm waiting for animation to complete everything is ok, but when I'm setting slow duration time and clicking quickly dots two divs are fading in at the same time. How to prevent it? jQuery:

function main() {
var $currentSlide = $("#slide_1");
var $prevDot = $(".current");
$('.dot').on('click',function() {

    var index = $(this).index() + 1;
    $prevDot.removeClass('current');
    $(this).addClass('current');
    $prevDot = $(this);
    $currentSlide.fadeOut(2000,function() {   
        $('#slide_'+index).fadeIn(2000);            
    });
    $currentSlide = $('#slide_'+index);

});

}

$(document).ready(main);

HTML:

<div id="wrapper">
<div id="content_wrap">
    <div id="slide_1"></div>
    <div id="slide_2"></div>
    <div id="slide_3"></div>
</div>
<div id="dots">
    <div class="dot current" id="first"></div>
    <div class="dot" id="second"></div>
    <div class="dot" id="third"></div>
</div>
<div id="text"></div>
</div>

Fiddle: https://jsfiddle.net/krz099/6advvq6g/


Solution

  • You need to set the "current slide" inside the timed animation, and stop the previous animation on click. Otherwise during the animation the current slide is still the previous one from the first click, regardless of new click.

    $currentSlide.stop().fadeOut(2000,function() {   
                $('#slide_'+index).fadeIn(2000); 
                $currentSlide = $('#slide_'+index);
    
            });
    

    JSFIDDLE: https://jsfiddle.net/ycLdvdzj/1/