jqueryscrolltoimage-replacement

jquery image replacement depending on scroll position only works properly after first load


I have a horizontal scrolling website and depending on the scroll position I have an image replacement. On first load of page while you scroll when it is time for the first image swap the image dissappears and then reappears. After that the problem dissapears. Below is my jquery code:

$(window).scroll(function(){
 if(($(window).scrollLeft() >= 0)&& ($(window).scrollLeft() <= 1040)){
      $(".wrapper").css('background','url(img/naboutus.png) 95% top no-repeat fixed');
  } else if(($(window).scrollLeft() >= 1041)&& ($(window).scrollLeft() <= 2840)){
      $(".wrapper").css('background','url(img/nwhatwedo.png) 95% top no-repeat fixed');
  } else if(($(window).scrollLeft() >= 2841)&& ($(window).scrollLeft() <= 4640)){
      $(".wrapper").css('background','url(img/ntheory.png) 95% top no-repeat fixed');
  } else if(($(window).scrollLeft() >= 4641)&& ($(window).scrollLeft() <= 8424)){
      $(".wrapper").css('background','url(img/nportfolio.png) 95% top no-repeat fixed');
  } else if(($(window).scrollLeft() >= 8424)&& ($(window).scrollLeft() <= 11124)){
      $(".wrapper").css('background','url(img/nclients.png) 95% top no-repeat fixed');
  }else {
      $(".wrapper").css('background','url(img/ncontacts.png) 95% top no-repeat fixed');
  }
  });

Is it because the images are not preloaded or is there a problem in my code?

The test site is on: http://karpouzaki.com/fade/

Any help would be appreciated.

Thanks


Solution

  • That is because the images aren't preloaded. Try this for relatively simple image preloading since you don't really need to wait until they are done in this case:

    $.each(["img/naboutus.png","img/nwhatwedo.png","img/ntheory.png","img/nportfolio.png","img/nclients.png","img/ncontacts.png"],function(i,url){
        var img = new Image();
        img.src = url;
    });
    

    Edit: Also, you can run this immediately, it doesn't have to wait until the document is ready since it doesn't rely on any DOM.