Search code examples
javascriptjqueryfadeinfadeoutjquery-effects

JQuery FadeOut, Load and FadeIn


I've got a following code for fadeOut, load another content and fadeIn, but I've got a problem, that sometimes, when the load function is very fast, it switches the loaded content even before the timeline completely fadeOut, so the effect is a bit weird at this case. How can I prevent this?

Note I want to load content immediately after click, so putting the load function into the first fadeTo callback function is not the solution. Thanks!

$(".switches li").click(function(evn) {
        $(".switches li").removeClass("active");
        $(evn.target).addClass("active");
        $(".timeline").fadeTo(400, 0, function(){
           $(this).css("visibility", "hidden");
        }); 
        $(".timeline").load("inc-timeline/"+evn.target.id+".html", function() {
            $(this).fadeTo(400, 100, function() {
                $(this).css("visibility", "visible");
                if(evn.target.id === "data-girls") {
                    $(".data-girls-powered").fadeIn(400);
                } else {
                    $(".data-girls-powered").fadeOut(400);
                }
            });
        });  
    });

Solution

  • Use start option of .animate(), .finish()

      // call `.load()` when `.fadeTo(400, 0)` starts 
      $(".timeline").finish().animate({opacity:0},{
        start: function() {
          // do asynchronous stuff; e.g., `.load()`
          $(this).load("inc-timeline/"+evn.target.id+".html", function() {
            // stop `.fadeTo(400, 0)` animation,
            // start animating to `opacity:1`
            $(this).finish().fadeTo(400, 1, function() {
              // do stuff
            });
          });
        },
        duration: 400        
      });
    

    $("button").click(function() {
      // call `.load()` when `.fadeTo(400, 0)` starts 
      $(".timeline").finish().animate({opacity:0},{
        start: function() {
          var el = $(this);
          // do asynchronous stuff; e.g., `.load()`
          $.Deferred(function(dfd) {
            setTimeout(function() {
              dfd.resolveWith(el)
            }, Math.floor(Math.random() * 3500))
          }).promise().then(function() {
            // stop `.fadeTo(400, 0)` animation,
            // start animating to `opacity:1`
            $(this).finish().fadeTo(400, 1, function() {
            });
          });
        },
        duration: 400        
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button>click</button>
    <div class="timeline">abc</div>