0

I am trying to create a jquery 'for loop' that is used to get image urls from an array and use them to change a background of a div with class ".mobile".

The array is filled up with 3 urls. The problem is that the first and second urls are ignored and the third image is displayed 3 times. Also, I tried inserting an alert to see what the "i" variable contains and the alert comes up 3 times after each other, iterating from 0 to 2 without the code being executed before each alert.

Here is the code:

$(document).ready(function(){
    var images = [ "url(images/image1.png)","url(images/image2.png)","url(images/image3.png)" ];        
    var i;
    for (i = 0; i < images.length; i = i+1) {
        $('.mobile').delay(2000).animate({'opacity': '0.0'}, 1000);
        $('.mobile').css("background-image", images[ i ]);
        $('.mobile').delay(2000).animate({'opacity': '1.0'}, 1000);
        alert(i);
    };

});

So to recap, I want to show each background image in the array with a delay before the next image appears.

I am still quite new to jQuery so any help would be greatly appreciated! :)

Amit
  • 15,217
  • 8
  • 46
  • 68
Steve-o-graph
  • 67
  • 1
  • 6

3 Answers3

2

Try

$(document).ready(function () {
    var images = ["url(http://placehold.it/32/ffff00)", "url(http://placehold.it/32/ff0000)", "url(http://placehold.it/32/000000)"];

    function render(images) {
        var img = images.shift();
        images.push(img);

        $('.mobile').delay(2000).animate({
            'opacity': '0.0'
        }, 1000, function () {
            console.log(img)
            $(this).css("background-image", img).delay(2000).animate({
                'opacity': '1.0'
            }, 1000, function () {
                render(images);
            });
        });
    }

    render(images)

});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

The problem lies with your JQuery selector, $('.mobile') will select all elements that match the class selector, so all your elements are having their background image change with each loop.

You could use eq(i) to select the correct element based on the index, like so:

for (i = 0; i < images.length; i = i+1) {
    var $item = $('.mobile').eq(i);
    $item.delay(2000).animate({'opacity': '0.0'}, 1000);
    $item.css("background-image", images[ i ]);
    $item.delay(2000).animate({'opacity': '1.0'}, 1000);
};
musefan
  • 47,875
  • 21
  • 135
  • 185
0

There are a few things. If the opacity is "0.0" then image will not be displayed. If you want something to be done after the animation is complete, pass a callback function.

halkujabra
  • 2,844
  • 3
  • 25
  • 35