jQuery - Switching background-image of an element

Asked

Viewed 692 times

5

I have a figure element 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 recover the path of each image and assign 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);
}

Only instead of assigning the image path the script returns Undefined! How can I fix this?

Code in the Jsfiddle

2 answers

5


One problem is that you are setting several setInterval, one for each image, which causes there to be a lot of competing timers to make changing the image being displayed.

You don’t need one for, but yes, only one setInterval with a control variable set somewhere in order to know which is the next image to be displayed.

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);

1

In the way .MAP() you must pass a stop before function() With some information, alt, as a array with all the information you want to manipulate.

According to the documentation jquery.

Ex:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.