0

I am trying to get one background image to fade into another using a very simple if statement. Currently my background images do not fade into one and another, they first fade onto a white background and then the other image fades in after, I would however like them to fade into each other directly. Secondly there seems to be an error with my images displaying, so when the the limit of the array (1) is reached in the if statement then it will set a simple currentBackground variable to 0, meaning the backgrounds should start from 0 in the array, however, this does not happen and sometimes the image same image is displayed repetitively.

            $(window).load(function() {
        var images = ['img/fitness-bg-2.jpg','img/runner-header.jpg'];
        var i = 0;

        function changeBackground() {
            $('#header').fadeOut(250, function(){
                $('#header').css('background-image', function () {
                    if (i >= images.length) {
                        i = 0;
                    }

                    return 'url(' + images[i++] + ')';
                });
                $('#header').fadeIn(500);
            })
        }
        changeBackground();
        setInterval(changeBackground, 5000);
    });
DaveDavidson
  • 206
  • 1
  • 8
  • 22
  • 1
    You can check out [this link](http://stackoverflow.com/questions/29749708/fade-in-fade-out-background-images-without-white-background) for the first problem. – davidhu Aug 22 '16 at 23:21
  • `setTimeout(changeBackground, 0);` will cause the `changeBackground` function to be called every time the JavaScript engine has a free slot in its execution queue (more or less, more here: http://stackoverflow.com/a/779785/215552). Since your function actually takes 3 seconds (one second to fade out the header, two seconds to fade back in, you're going to see a lot of problems. Instead, put the next call to `changeBackground` in the callback to `fadeIn`... – Heretic Monkey Aug 22 '16 at 23:21

0 Answers0