MKC
MKC

Reputation: 188

jQuery Looping Through Background Images

I'm working on a jQuery function that I'm trying to use to cycle through different background images fading in and out. For some reason it is only changing from the default background image to the second one (contact_banner) and then back to the same one again.

Any help would be much appreciated, I'm sure it's something simple but I can't seem to work it out.

$(document).ready(function () {

function slider(){

    $('#cover').delay(3000).fadeOut(1000);
    $('#cover').css("background-image", "url('images/classes-cover.jpg')");
    $('#cover').fadeIn(1000);

    $('#cover').delay(3000).fadeOut(1000);
    $('#cover').css("background-image", "url('images/contact_banner.png')");
    $('#cover').fadeIn(1000, slider);
}   
slider();
});

Upvotes: 1

Views: 1376

Answers (2)

garryp
garryp

Reputation: 5766

jQuery fade is asynchronous. Use callbacks to fire the next event once the first is done.

$('#cover').fadeIn(1000, function() { $('#cover').fadeIn(1000, ... ); });

Have a look at this fiddle I've prepared for you http://jsfiddle.net/xu7sbofv/.

The important thing to understand is that the function does not block on fadeIn() or delay() because the calls are asynchronous. This is why you must supply callback functions.

Upvotes: 2

MKC
MKC

Reputation: 188

Managed to find a solution to this, a bit of a neater implementation too:

var imgSrcs =[
    "images/class-banner/running-group_banner2.png",
    "images/class-banner/running-group_banner3.png",
    "images/class-banner/running-group_banner1.png",
];

$('#cover').delay(1000).fadeIn(1000, animateBackground());

function animateBackground() {

    window.setTimeout(function(){

        var url = imgSrcs[imgSrcs.push(imgSrcs.shift()) - 1];

        $('#cover').delay(4000).fadeOut(1000, function(){

            $(this).css("background-image", "url(" + url + ")")

        }).fadeIn(1000, animateBackground())

    });
}

Upvotes: 0

Related Questions