maverickosama92 maverickosama92 - 22 days ago 10
jQuery Question

jquery images active/inactive loading

Here is my code

$(function(){
var $list = $('.my-loading-list'),
$imgs = $list.find('img'),
animateImages = function(){
var active = 0;
setInterval(function(){
active = $list.find('img.active').index();
if(active > $imgs.length){
active = 0;
} else {
active++;
}
$imgs.attr('src', 'https://cdn3.iconfinder.com/data/icons/cool-me-down-thermometers/70/Weather_cloudy_grey-128.png');
$imgs.eq(active).addClass('active').attr('src', 'https://cdn3.iconfinder.com/data/icons/vibrant-weather/70/Colour_Weather_cloudy_grey-128.png');
}, 300);

setInterval(function(){
$imgs.removeClass('active');
}, 600);
};

animateImages();
});


And here is the snippet:

https://jsfiddle.net/8d4xfjgt/

I need to animate the third image as well. one and two are changing their source but not the third one.

Please suggest.

Answer

Do you want to change the 3 images, one by one like this, or all at the same time? The problem is this value isn't updating correctly active = $list.find('img.active').index(). It's taking values -1,0 alternatively

$(function(){
        var $list = $('.my-loading-list'),
            $imgs = $list.find('img'),

            animateImages = function(){
                var active = 0;
                setInterval(function(){



                    if(active > $imgs.length){
                        active = 0;
                    } else {
                        active++;
                    }
                    $imgs.attr('src', 'https://cdn3.iconfinder.com/data/icons/cool-me-down-thermometers/70/Weather_cloudy_grey-128.png');
                    $imgs.eq(active).addClass('active').attr('src', 'https://cdn3.iconfinder.com/data/icons/vibrant-weather/70/Colour_Weather_cloudy_grey-128.png');
                }, 150);

                setInterval(function(){
                    $imgs.removeClass('active');
                }, 150);
            };

        animateImages();
    });