<!DOCTYPE html>
<html>
<head>
<title>Random Image</title>
<style>
img {
width:150px;
height:150px;
border:1px solid black;
}
</style>
<script>
//Red images array
var redImages = ["./images/red/red001.jpg", "./images/red/red002.jpg", "./images/red/red003.jpg", "./images/red/red004.jpg", "./images/red/red005.jpg", "./images/red/red006.jpg"];
//Blue images array
var blueImages = ["./images/blue/blue001.jpg", "./images/blue/blue002.jpg", "./images/blue/blue003.jpg", "./images/blue/blue004.jpg", "./images/blue/blue005.jpg", "./images/blue/blue006.jpg"];
window.onload = function() {
//When the document has loaded, get random pictures
RandomBluePicture();
RandomRedPicture();
};
function RandomBluePicture() {
var img = blueImages[ randomInt(0, blueImages.length - 1) ];
var tag = document.getElementsByTagName("img")[0]; //First image tag
alert("Image selected: " + img);
tag.setAttribute("alt", img);
tag.setAttribute("src", img);
tag.setAttribute("title", img);
}
function RandomRedPicture() {
var img = redImages[ randomInt(0, redImages.length - 1) ];
var tag = document.getElementsByTagName("img")[1]; //Second image tag
alert("Image selected: " + img);
tag.setAttribute("alt", img);
tag.setAttribute("src", img);
tag.setAttribute("title", img);
}
function randomInt(Min, Max) {
return Math.floor(Math.random() * (Max - Min + 1) + Min);
}
</script>
</head>
<body>
<button onclick="RandomBluePicture()">Click to get random blue picture</button><br>
<img>
<p> </p>
<button onclick="RandomRedPicture()">Click to get random red picture</button><br>
<img>
</body>
</html>
Comments