0

I am changing my background image from this code

jQuery(window).load(function(){
var images = ['blaa.jpg','sdsd.jpg'];
var i = 0;
setInterval(function(){

    jQuery('#absolute-c').css('background-image', function() {
        if (i >= images.length) {
            i=0;
        }
        return 'url(' + images[i++] + ')';      
    });
}, 3000);
})

how do .animate and load first background without delay. due to setInterval my first background also show after 3 sec

3
  • What is "cycle" and "rotate"?
    – Blender
    Aug 12, 2012 at 1:19
  • 2
    if you want the 1st bg image to appear immediately - set it in CSS Aug 12, 2012 at 1:28
  • thanks did it, and please tell me how do I do .delay or animate
    – user1289939
    Aug 12, 2012 at 1:31

1 Answer 1

1

You can do create a function for this and use it in the setInterval:

jQuery(window).load(function(){
    var images = ['blaa.jpg','sdsd.jpg'];
    var i = 0;

    function changeBackground() {
        jQuery('#absolute-c').css('background-image', function() {
            if (i >= images.length) {
                i=0;
            }
            return 'url(' + images[i++] + ')';      
        });
    }
    // Call it on the first time
    changeBackground();
    // Set an interval to continue
    setInterval(changeBackground, 3000);
});

Another solution, and I think is much better, is to use setTimeout instead:

jQuery(window).load(function(){
    var images = ['blaa.jpg','sdsd.jpg'];
    var i = 0;
    var timeoutVar;

    function changeBackground() {
        clearTimeout(timeoutVar); // just to be sure it will run only once at a time

        jQuery('#absolute-c').css('background-image', function() {
            if (i >= images.length) {
                i=0;
            }
            return 'url(' + images[i++] + ')';      
        });

        // call the setTimeout every time to repeat the function
        timeoutVar = setTimeout(changeBackground, 3000);
    }

    // Call it on the first time and it will repeat
    changeBackground();        
});
2
  • how to add .fade or .animate effect
    – user1289939
    Aug 13, 2012 at 2:23
  • What and when exactly do you want to animate? Aug 13, 2012 at 3:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.