0

I tried to get the "background image change on scroll" working on my page. but while scrolling the changes are flickering. I couldn't find a solution in other threads.

This is what I have:

jquery:

$(function(){
$(document).scroll(function () {


    if ($(this).scrollTop() > 1) {
        $('body').css({
            backgroundImage: 'url("img/picture1.jpg")'
        });
    }


      if ($(this).scrollTop() > 800) {
        $('body').css({
            backgroundImage: 'url("img/picture2.jpg")'
        });
    }

CSS:

body {
    background: url('../img/picture1.jpg');
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-size:cover;
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
Dennis
  • 137
  • 1
  • 2
  • 14
  • Can you please show a live version or a http://jsfiddle.net/. – ggdx Dec 08 '13 at 00:42
  • 1
    You are constantly setting the background image, over and over again. You need to store the state in a variable, so ou only set the background once you first pass the 800px mark etc. – HaukurHaf Dec 08 '13 at 00:52
  • thank you, but can you explain this a bit more precise. Im new to jquery... :/ – Dennis Dec 08 '13 at 00:58

1 Answers1

0

The flickering is probably due to the second image loading. You can preload the second image using javascript's native Image object:

var newImg = new Image();
newImg.src = 'img/picture2.jpg';

See this jsfiddle.

Mark S
  • 3,789
  • 3
  • 19
  • 33
  • Thanks this works! But how can i go for more pictures? This wont work: http://jsfiddle.net/VjmfY/2/ – Dennis Dec 08 '13 at 10:01
  • You can create a function and pass all the images as arguments for preloading: [jsfiddle.net/VjmfY/3/](http://jsfiddle.net/VjmfY/3/) – Mark S Dec 08 '13 at 11:39
  • I'm not entirely sure when you want to change the background-image, but if you want to preload and change it consistently like per 800 scroll increment. I made a solution that might help you, [**jsfiddle.net/VjmfY/4/**](http://jsfiddle.net/VjmfY/4/). – Mark S Dec 08 '13 at 12:59
  • thank you..the images should change on different pixel values, like 800, 1200, 1800... – Dennis Dec 08 '13 at 15:47