-1

I am looking for a way to show a random image upon hovering some text or a div.

Tried a few CSS ways but I don't think it's possible without jQuery or Javascript, either is fine.

My (way overcomplicated) idea was using a random script such as

Math.floor(Math.random() * 10);

then using a few nested if statements (I know) to add or remove classes on the images files which 4/5 (orwhatever) would have hidden tags and the random one would get it removed. I couldn't even figure that out and I definitely think its a messy way to solve this. Does anyone have a better idea? Thanks so much!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • `without Jqeury or Java` There is a very large difference between Java and Javascript... – CertainPerformance Aug 15 '18 at 02:14
  • Ah, I gotcha. Edited. – Griffin Malone Aug 15 '18 at 02:18
  • 2
    It's kinda possible using CSS..... **BUT** , and this is a big **BUT** (and I can not lie), you would need to call a server side service that generates the image, even then it would possibly be cached on the browser. Javascript/jQuery is a better option. – Jon P Aug 15 '18 at 02:24
  • 1
    When you say random images. Do you have those images located some where? If so you can name them 1.jpg to 999999999999.jpg. on hover show a random image.. It's just an idea.. – Praveen Govind Aug 15 '18 at 02:26
  • Yes, local files. @JonP do you have a javascript solution or idea? – Griffin Malone Aug 15 '18 at 02:27

1 Answers1

2

You could have the image urls in an array and pick one randomly when the user hovers over the text.

e.g.

var arr = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];

function getRandomImage() {
  var index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

$("#div").hover(
  function() {
    var image = getRandomImage();
    $("#img").attr("src", image);
    console.log(image);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="div">hover over me</div>
<img id="img" />
H77
  • 5,859
  • 2
  • 26
  • 39
  • 1
    You might want to [preload the images](https://stackoverflow.com/questions/3646036/javascript-preloading-images) so the image does not have to download on the initial hover – Jon P Aug 15 '18 at 02:41
  • True. Some tweaking on this and this is perfect! Thank – Griffin Malone Aug 15 '18 at 02:43
  • You could optimise this by changing the image on the mouseout (the opposite of hover). That way all logic is handled when the user isnt watching or expecting anything :) – Martijn Aug 15 '18 at 14:00