Search code examples
javascriptjqueryfadeinfadeout

jQuery function looping again and again


I want to create an animation where with scrolling background image of the Website changes. Changing happens with a fadeIn and fadeOut effect, But fading effect happens multiple times due to scroll function.

JSFiddle

Jquery Code: 
var styles01 = {"background" : "url(https://iso.500px.com/wp-content/uploads/2016/02/cover.jpg) fixed",
                 "background-size":"cover"}; 
var styles02 = {"background" : "url(http://www.mybligr.com/wp-content/uploads/2017/02/beautiful-lake-wallpaper-nature-photos-pics-images-pictures-16.jpg) fixed",
            "background-size":"cover"};
var styles03 = {"background" : "url(https://cdn.fodors.com/ee/files/slideshows/9-derwent-water-lake-district-england.jpg) fixed",
            "background-size":"cover"};

$(window).scroll( function() {
 if ($(window).scrollTop() >= 50 && $(window).scrollTop() <= 150) {
     $(".wrap").fadeOut(200);
    $(".wrap").css(styles01);
     $(".wrap").fadeIn(200);
  } 
 if ($(window).scrollTop() >= 150 && $(window).scrollTop() <= 250) {
      $(".wrap").fadeOut(200);
    $(".wrap").css(styles02);
       $(".wrap").fadeIn(200);
  }
 if ($(window).scrollTop() < 50) {
     $(".wrap").fadeOut(200);
    $(".wrap").css(styles03);
      $(".wrap").fadeIn(200);
  }
});

Solution

  • It appears to be a timing issue, because you're trying to re-style and re-fade before the initial fade-out is done. This is an asynchronous operation:

    $(".wrap").fadeOut(200);
    

    So anything that needs to happen after this operation should be placed in its callback, not placed immediately after this line of code. Something like this:

    $(".wrap").fadeOut(200, function () {
        $(".wrap").css(styles01);
        $(".wrap").fadeIn(200);
    });
    

    Updated fiddle.