Predrag Grbatinic
Predrag Grbatinic

Reputation: 65

Random pictures from start slider js

i have a simple image slider and im pretty much new to JS. This is HTML of slider.

<a class="thumb-box scroll-to-section" href="#people">
  <img src="someimg" class="peoples-img" style="display: none;">
  <img src="someimg2" class="peoples-img" style="display: none;">
  <img src="someimg3" class="peoples-img" style="display: none;">
  <img src="someimg4" class="peoples-img" style="display: none;">                
  <h3 class="thumb-box__title">People</h3>
</a>

and here is the JS code

var myIndex = 0; carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("peoples-img");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}
    x[myIndex-1].style.display = "block";
    setTimeout(carousel, 2000); // Change image every 2 seconds
}

slider works fine img by img, but i want to make slider to shuffle images. And everytime I reload page to open different image, any suggestion?

Upvotes: 1

Views: 1910

Answers (2)

Marcos Nakamine
Marcos Nakamine

Reputation: 1436

Try this

var x = document.getElementsByClassName("peoples-img");
var randomIndex = new Array();

function shuffle() {
    for(i=0; i<x.length; i++){
        randomIndex.push(i);
    }

    //http://stackoverflow.com/a/18650169/1582080
    randomIndex.sort(function() {
        return .5-Math.random();
    });
}

function carousel() {
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}
    x[randomIndex[myIndex-1]].style.display = "block";
    setTimeout(carousel, 2000); // Change image every 2 seconds
}

var myIndex = Math.floor(Math.random()*x.length);
shuffle();
carousel();

Upvotes: 1

Bouramas
Bouramas

Reputation: 1168

Here you can find instructions on how to generate a random number. Use this number to access a random element in your array. This way each time you will show a random image.

Upvotes: 1

Related Questions