user6260659 user6260659 - 7 months ago 12
Javascript Question

What should I do to change this array from random to appearing in sequence on page refresh?

Here is the code...
I'm new to this. Thanks in advance for any advice!

<script type="text/javascript">
$(function () {
var url = "http://localhost:8888/wordpress_hattie/wp-content/uploads/2015/04/",
imgArray = [url+"paper_shape3.svg",
url+"mustard_shape2.svg",
url+"alt_shape.svg"],
randomNumber = Math.floor((Math.random() * imgArray.length)),
baseUrl = "url('" + imgArray[randomNumber] + "')";
$(".par_layer").css('background-image', baseUrl);
})();
</script>

Answer

You could store the index of the previously used image in localStorage and increment the index each time the script runs.

var basePath = 'http://localhost:8888/wordpress_hattie/wp-content/uploads/2015/04/';
var fileNames = ['paper_shape3.svg', 'mustard_shape2.svg', 'alt_shape.svg'];
var index = 0;

// Get last index from localStorage if present and increment it by 1.
if (localStorage.getItem('index') !== null) {
  index = Number(localStorage.getItem('index')) + 1;
}

// Reset index to 0 if it exceeds the bounds of fileNames.
if (index >= fileNames.length) {
  index = 0;
}

// Store index in localStorage for later use.
localStorage.setItem('index', index);

$('.par_layer').css('background-image', 'url(' + basePath + fileNames[index] + ')');