Hi_I’m trying to make a random number appear inside an img src=
address in a div, so that a random image is generated every time the div is loaded.
I have 10 images and their directory addresses are:
"pictures/number1.jpg"
"pictures/number2.jpg"
"pictures/number3.jpg"
................
"pictures/number10.jpg"
I’m able select one of these at random with the following Javascript:
var num = Math.floor(Math.random() * 10 + 1);
img.src = "pictures/number" +num +".jpg";
This generates a random number between 1 and 10 and places it inside the address to locate the image.
This works perfectly when the img.src
is used inside the Javascript file, but I’m wondering if it’s possible to use this method when img src=
is part of a HTML page. I’m trying to apply a similar process to the following HTML code:
<script>
var num = Math.floor(Math.random() * 10 + 1);
randomimage = "pictures/number" +num +".jpg";
</script>
<div id="JohnDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1" /> </div>
<div id="JackDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1" /> </div>
<div id="JaneDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1 /> </div>
This isn't working, it's just showing me the alt=
message. I'm not sure if I've defined randomimage
correctly.
I'm really confused about how to go about doing this the right way, any help would be greatly appreciated!
Thanks in advance!
Edit
As to why your code isn't working: You can't apply
randomimage
to the source of the image in plain HTML. You have to do that using Javascript. To do that you have to select the element you want to manipulate and modify thesrc
attribute through Javascript.Since you tagged this with jQuery I'll start by using it!
You can use an
.each()
loop on yourmyClass1
class to iterate over each image and change the image src for each image with the given class.Fiddle
For testing purposes the image's
alt
attribute is set to thesrc
of the image.Edit
Here is another solution using plain Javascript.
Fiddle