jQuery - Toggle background-image of an element

5

I have an element figure with a series of images inside:

<figure class="MiniModImgSlider">
  <img src="img01.jpg" alt="img01">
  <img src="img02.jpg" alt="img02">
  <img src="img03.jpg" alt="img03">
  <img src="img04.jpg" alt="img04">
  <img src="img05.jpg" alt="img05">
</figure>

Note: Images are with display: none.

I want to retrieve the path of each image and assign it to the background of the figure element every 3 seconds. For this I made this script:

var imgs = $(".MiniModImgSlider img").map(function() 
{
  return $(this).attr('src');
});

for (var i = 0; i <= imgs.length; i++) 
{
  setInterval(function()
  {
    $(".MiniModImgSlider").css('background-image', 'url('+imgs[i]+')');
  },1000);
}

But instead of assigning the path of the image the script returns undefined! How can I resolve this?

Code in JSFiddle

    
asked by anonymous 14.04.2014 / 18:21

2 answers

5

One problem is that you are setting multiple setInterval , one for each image, which means there are a lot of timers competing to make changes to the image being displayed.

You do not need a for , but only a setInterval with a control variable defined somewhere, so you know which is the next image to display.

Example in jsfiddle

var imgs = $(".MiniModImgSlider img")
.map(function()
     {
         return $(this).attr('src');
     });

var imgIndex = 0;
setInterval(function()
            {
                var url = imgs[imgIndex++ % imgs.length];
                $(".MiniModImgSlider")
                .css('background-image', 'url('+url+')');
            },1000);
    
14.04.2014 / 18:45
1

In the .MAP() method you should pass a parameter before function() With some information, eg alt , as array with all the information you want to manipulate.

According to Jquery documentation .

Ex:

var arr = [1,2,3,4,5];
var imgs = $(".MiniModImgSlider img").map(arr,function(){
    FAZ ALGUMA COISA
};
    
14.04.2014 / 18:50