0

This may be a bit of a stretch, but I have a webpage with 3 small image placeholders at the bottom.

I'd like each placeholder to be able to display a random image with a link every time the page is loaded.

For example, at the moment I have:

<div class="col-xs-12 col-sm-12 col-md-4 homeFooter1">
<a href="Link-1"><img src="/image-1.jpg" alt="Image 1"></a>
</div>
<div class="col-xs-12 col-sm-12 col-md-4 homeFooter2">
<a href="Link-2"><img src="/image-2.jpg" alt="Image 2"></a>
</div>
<div class="col-xs-12 col-sm-12 col-md-4 homeFooter3">
<a href="Link-3"><img src="/image-3.jpg" alt="Image 3"></a>
</div>

I'd like to have "homeFooter1" choose between 3 different images - each with their own link to different pages, and the same for "homeFooter2" & "homeFooter3".

The images and links don't necessarily conform to a particular pattern. e.g. I might want to choose between: Pet-Food, Dog-Biscuits, Fish-Food in the first placeholder, with their links being petfood, dogsnacks and aquatics.

Hopefully this makes sense! I have seen examples of choosing an image from an array, but not an image with corresponding link.

The easiest way would probably be to have all of the divs on the page, and using an array to hide/unhide, but I'm aware of the user's bandwidth.

Thanks in advance!

Gary
  • 101
  • 1
  • 10
  • Does this answer your question? [Generating random whole numbers in JavaScript in a specific range?](https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range) – Pete Mar 20 '20 at 13:47
  • hide them all with css and show one depending on a random number generated with js? If you are bothered about bandwidth, then just insert / replace the html with js rather than starting with it on the page – Pete Mar 20 '20 at 13:48

1 Answers1

0

You should use two arrays or a dictionary and then a random generator. Use Jquery to append the images and links to page like below. This way you wont have to type out each div and this is more efficient.

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>


<div class="col-xs-12 col-sm-12 col-md-4 homeFooter1" id="placeholder"></div>

<script>

var images = ["/image-1.jpg", "/image-2.jpg", "/image-3.jpg"];
var links = ["http://google.com","http://msn.com","http://stackoverflow.com"];

//below is the random number generator the 3 is the upper limit int and 1 is the lower limit exclusive

var currImage = Math.floor((Math.random() * 3) + 1);
//array for images


$(document).ready(function(){
  $("#placeholder").append("<a href='" + links[currImage] + "'><img src='" + images[currImage] +"' alt='Image 1'></a>");
  });


</script>