I currently have the code below which successfully sets a random image from an array as .wrapper‘s background. I’d like to have another variable (string) that is permanently paired with each specific image so that when an image is randomly selected, its particular string is also passed in. So if foo.jpg is randomly selected, variable x is set to ‘foo’, but if bar.jpg is randomly selected, variable x is set to ‘bar’.
Any ideas how this can be achieved? Possibly with a JSON object?
my code:
var images = ["foo.jpg", "bar.jpg", "baz.jpg", "qux.jpg"];
function getImage() {
return images[Math.floor(Math.random() * images.length)];
}
$('.wrapper').css({
'background' : 'url(' + getImage() + ') no-repeat center center fixed'
});
Let me know any questions you may have.
Thanks
You can make your array an array of objects instead where each object in the array contains both the url and the tag. You randomly select one of the objects and can then separately access both the url and the tag:
Or, if the tag is always just the base of the image name so you can parse it out of the url, you could do this: