I'm showing an image on a page, and the image is called from an array of images that I'm accessing sequentially. Every time the page is reloaded, the next image in the array is shown. I'm saving to local storage to keep track of what image was last shown so that if the page is closed they will start where they left off next time. The images are located on a CDN, and they are subject to change or be removed, but when the array tries to access them it fails. Is there a way to skip array images when they can't be found and move on to the next one? I appreciate any help!
This is what I have so far:
$(function background() {
var images = [
"image1.png",
"image2.png",
"image3.png",
"image4.png",
"image5.png",
"image_bookend.png"
];
// Check to see if localStorage exists before
// we do anything
function hasLocalStorage() {
try {
localStorage.setItem("count2", 0);
if (localStorage.getItem("count2") === "0") {
return true;
}
} catch (e) {
return false;
}
return false;
}
// Fetch the count from localStorage. Because it's
// saved as a string we need to coerce it to a number
let count = Number(localStorage.getItem("count2"));
$("#image").css({
"background-image":
"url(https://res.cloudinary.com/image/upload/v1636154685/images/" +
images[count] +
")"
});
// Increase the count
count++;
// If the count is the length of the array (minus one
// because the array is indexed-based) set the
// localStorage count to zero, otherwise save the count
if (count === coupons.length - 1) {
localStorage.setItem("count2", 0);
} else {
localStorage.setItem("count2", count);
}
});