Alan_dj
Alan_dj

Reputation: 133

Random images load without repeat

Hi I found a script which loads images one after another into my div element. Everything works fine, but I would like it to load random images which do not repeat in a circle of all images.length.

Since I'm a total newb in this I tried to do something but most of the time I am able to load random images but without repeat check.

If you can, please help.

Thank you all in advance!

<script src="js_vrt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
//Initial Background image setup
image.css('background-image', 'url(' + images[i++] + ')');
//Change image at regular intervals
setInterval(function() {

image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1500);
});
if (i == images.length)
  i = 0;
}, 5000);
});
</script>

Upvotes: 3

Views: 2096

Answers (3)

RoboYak
RoboYak

Reputation: 1482

Here is a complete object that takes in an array of image urls, and then displays them randomly until it has shown them all. The comments should be pretty explanatory, but feel free to ask questions if I didn't explain something enough. Here is a fiddle

//Object using the Revealing Module pattern for private vars and functions
var ImageRotator = (function() {
  //holds the array that is passed in
  var images;
  // new shuffled array
  var displayImages;
  // The parent container that will hold the image
  var image = $("#imageContainer");
  // The template image element in the DOM
  var displayImg = $(".displayImg");
  var interval = null;

  //Initialize the rotator. Show the first image then set our interval
  function init(imgArr) {
    images = imgArr;
    // pass in our array and shuffle it randomly. Store this globally so
    // that we can access it in the future
    displayImages = shuffle(images);
    // Grab our last item, and remove it
    var firstImage = displayImages.pop();
    displayImage(firstImage);
    // Remove old image, and show the new one
    interval = setInterval(resetAndShow, 5000);
  }
    // If there are any images left in our shuffled image array then grab the one at the end and remove it.
  // If there is an image present in the Dom, then fade out clear our image
  // container and show the new image
  function resetAndShow() {
    // If there are images left in shuffled array...
    if (displayImages.length != 0) {
      var newImage = displayImages.pop();
      if (image.find("#currentImg")) {
        $("#currentImg").fadeOut(1500, function() {
          // Empty the image container so we don't have multiple images
          image.empty();
          displayImage(newImage);
        });
      }
    } else {
     // If there are no images left in the array then stop executing our interval.
      clearInterval(interval);
    }

  }
    // Show the image that has been passed. Set the id so that we can clear it in the future.
  function displayImage(newImage) {
    //Grab the image template from the DOM. NOTE: this could be stored in the code as well.
    var newImg = displayImg;
    newImg.attr("src", newImage);
    image.append(newImg);
    newImg.attr("id", "currentImg");
    newImg.fadeIn(1500);
  }
    // Randomly shuffle an array
  function shuffle(array) {
    var currentIndex = array.length,
      temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {
      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array;
  }

  return {
    init: init
  }
});
var imgArr = [
  "https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg",
  "https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg",
  "https://i.ytimg.com/vi/icqDxNab3Do/maxresdefault.jpg",
  "http://www.funny-animalpictures.com/media/content/items/images/funnycats0017_O.jpg",
  "https://i.ytimg.com/vi/OxgKvRvNd5o/maxresdefault.jpg"
]
// Create a new Rotator object
var imageRotator = ImageRotator();
imageRotator.init(imgArr);

Upvotes: 1

you can try to make and array filled with 0's

var points = new Array(0,0,0, 0) 
//each one representing the state of each image
//and after that you make the random thing 
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
while (points[i]!=1){
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length));
var ist;
}
setInterval(function() {

image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
points[i]=1;
image.fadeIn(1500);
});

Upvotes: 0

Franklin Satler
Franklin Satler

Reputation: 320

You can use the shuffle method explained on the answer below.

How can I shuffle an array?

And get the first element on your array

image.css('background-image', 'url(' + images[0] + ')');

You may find a issue on this method, when the same image get loaded after shuffle the array. In this case, I recommend you to store in a variable the name of the last image shown, and before the array get shuffled, just test if the first element is equal the last image.

var lastImageLoaded ='';

setInterval(function() {
   shuffle(images);
   var imageUrl = images[0];
   if(lastImageLoaded !== ''){ // Handle the first load
      while(lastImageLoaded === images[0]){
          shuffle(images);
      }
   }
   lastImageLoaded = image;
   image.fadeOut(1500, function() {
      image.css('background-image', 'url(' + imageUrl + ')');
      image.fadeIn(1500);
});

Upvotes: 1

Related Questions