Devin Gibson
Devin Gibson

Reputation: 111

With JavaScript how would I increment strings using an array to create a loop?

I'm trying to make a web page that has its wallpaper change every time you refresh. I'd like it to display the next image in the array every time the page is refreshed. So every refresh works its way through the list until the end, and then starts over.

Right now I'm using an array and accessing it with a random index, but I need to access it using one that increases by 1 each time, and once I reach the array length I need it to start over again... Right now I'm using this (which took me forever to figure out):

$(function background() {
    var images = [
      "wallpaper1.jpg",
      "wallpaper2.jpg",
      "wallpaper3.jpg",
      "wallpaper4.jpg"
    ];
    $("#hero").css({
      "background-image":
        "url(images/wallpapers/" +

        images[Math.floor(Math.random() * images.length)] 
        
        + ")"
    });
  });

I have found out about incrementing numbers in an array using this:

var arr = [1,2,3,4];
arr = arr.map(function(val){return ++val;});
console.log(arr);

But I can't seem to get the number solution to work with strings. I'm ultra new at all this and I am losing my mind :/

Upvotes: 3

Views: 773

Answers (4)

Lakshaya U.
Lakshaya U.

Reputation: 1171

Possible, but the persistence is only becuase of the localStorage

Hey! Check this out. This basically selects an image from the array and then changes the background continuously according to the current image. If the last image (when the user last visited the page) was wallpaper4.jpg, the next would be automatically the wallpaper1.jpg.

Assuming that the target browser has localStorage enabled, this would be the JavaScript code

var images = [
    "wallpaper1.jpg",
    "wallpaper2.jpg",
    "wallpaper3.jpg",
    "wallpaper4.jpg"
    ];

getBgImage = () => {
    var lastImage = localStorage.getItem("wallpaperIdx");
    if (lastImage && images.indexOf(lastImage) < (images.length - 1) && images.indexOf(lastImage) >= 0) {
        localStorage.setItem("wallpaperIdx", images[(images.indexOf(lastImage) + 1)]);
        return images[(images.indexOf(lastImage) + 1)];
    } else if (images.indexOf(lastImage) === (images.length - 1)) {
        localStorage.setItem("wallpaperIdx", images[0]);
        return images[0];
    } else {
        localStorage.setItem("wallpaperIdx", images[0]);
        return images[0];
    }
}

$(function () {
    setInterval(() => {
        var image = getBgImage();
        $('#hero').css({
            "background-image": `url("images/wallpapers/${image}")`,
            "transition": "1s"
        });
    }, 1000)
    clearInterval();
});

$(() => {
    $(window).on("load", () => {
        document.getElementById("hero").style.backgroundImage = `url("images/wallpapers/${image}")`;
    })
})

Upvotes: 1

Mayank Kumar
Mayank Kumar

Reputation: 61

<!DOCTYPE html>
<html>
<body>
<script>
// Checking if the Local Storage feature is available.
if (typeof(Storage) !== "undefined") {
  // If it is available, check if there is a value stored by the name 'val'.
  if(localStorage.getItem("val") != null) {
    // If yes increase it by 1.
    localStorage.setItem("val", parseInt(localStorage.getItem("val")) + 1);
  }
  else {
    // If no then create one and set it to 1.
    localStorage.setItem("val", 1);
  }
  // Printing the value on the console and the page to check if it is working (You can remove this later.)
  console.log(localStorage.getItem("val"));
  document.write(localStorage.getItem("val"));

} 
// If it is not available notify the user.
else {
  console.log("Sorry, your browser does not support Web Storage...");
  document.write("Sorry, your browser does not support Web Storage...");
}

var num = parseInt(localStorage.getItem("val"));
</script>
</body>
</html>

Local Storage is a feature is in HTML. It can be used to store data in the tab and will be there as long as the tab isn't closed. So, now whenever you reload your page you will get the next number starting from one.

Upvotes: 1

Andy
Andy

Reputation: 63524

You need to save a counter to localStorage that you can retrieve on each page load, increment,, make the check, and then save again.

$(function () {

    const images = [
      'wallpaper1',
      'wallpaper2',
      'wallpaper3',
      'wallpaper4'
    ];

    // We must check to see if localStorate exists before
    // we do anything
    function hasLocalStorage() {
      try {
        localStorage.setItem('count', 0);
        if (localStorage.getItem('count') === '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('count'));

    $("#hero").css({
      'background-image': `url(${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
    // localStorate count to zero, otherwise save the count
    if (count === images.length - 1) {
      localStorage.setItem('count', 0);
    } else {
      localStorage.setItem('count', count);
    }

});

Upvotes: 2

erikvold
erikvold

Reputation: 16528

You can add a helper function to do this:

var getNextImage = (() => {
  var i = 0;

  return () => {
    if (i >= images.length)
    {
      i = 0;
    }

    return images[i++];
  };
})();

and then replace the images[Math.floor(Math.random() * images.length)] call with getNextImage()

Like so:

$(function background() {
    var images = [
      "wallpaper1.jpg",
      "wallpaper2.jpg",
      "wallpaper3.jpg",
      "wallpaper4.jpg"
    ];

    var getNextImage = (() => {
      var i = 0;
    
      return () => {
        if (i >= images.length)
        {
          i = 0;
        }

        return images[i++];
      };
    })();

    $("#hero").css({
      "background-image":
        "url(images/wallpapers/" + getNextImage() + ")"
    });
  });

Upvotes: 1

Related Questions