Reputation: 11
Thanks to you guys I was able to use the javascript below to change the background image randomly from my website every time it is refreshed. This was a pain because the image location was on the .css document and not in the .html.
I need for the images to display in ascending order, "1.jpg, 2.jpg, 3.jpg, etc" Once it reaches the last number it starts again with 1.jpg.
I've been researching and trial and error for 2 days with no luck.
<script type="text/javascript">
var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg'];
$('#parallax-header').css({'background-image': 'url(images/parallax/' +
images[Math.floor(Math.random() * images.length)] + ')'});
</script>
Upvotes: 1
Views: 1376
Reputation: 206171
Using localStorage (similar to Josh's answer)
var images = ['foo.jpg', 'bar.jpg', 'baz.jpg']; // Add as many as y w
var n = +localStorage.imgN || 0; // Use `0` if localStorage was never set before
$('#parallax-header').css({backgroundImage: 'url(images/parallax/' + images[n] + ')'});
localStorage.imgN = ++n % images.length; // re-set by incrementing and loop
Upvotes: 0
Reputation: 19772
For that to happen, the browser will need to remember what the previous image was before refresh. This can happen with either cookies or localStorage
. If your array has the images in ascending order already, you can simply store the last index of the image in the browser's storage and then increment it by one on every refresh.
// coerce the index to number just in case; if it is null, set it to 0
var i = +localStorage.getItem('i') || 0,
next = 0,
images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg'];
if(i === images.length - 1) {
next = 0;
} else {
next = i++;
}
localStorage.setItem('i',next);
$('#parallax-header').css({'background-image': 'url(images/parallax/' +
images[i] + ')'});
Here is the compatibility table from MDN for localStorage:
If you need a polyfill, check out Web Storage (LocalStorage and SessionStorage) from HTML5 Cross Browser Polyfills.
Upvotes: 1