I'm a bloody beginner. Please don't be impatient with me :-) Sorry, my english is not the best...
My goal is, to change randomly a shown image, by clicking a button. Of course, I could find a complete code for my request, but I want to train my skills and I tried to find a way, doing it. I guess, I found a way, but...
-
When I click the button, with the variable on line 11, nothing happens, but when I put the URL instead of the variable (copied from the console from line 22), it goes to the according picture. I don't get it...
-
When my "imageCount" is full, i get an error
Is my hole way doeing it, too complicated? I'm trying since hours. Maybe I'm just not seeing the obvious. Can anyone help me?
HTML:
<html>
<head>
<meta charset="utf-8">
<link href="./style/main.css" rel="stylesheet">
<title>Choose Image randomly</title>
</head>
<body>
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
<script src="./script/main.js" type="text/javascript"></script>
</body>
</html>
JAVASCRIPT:
var imageCount = [];
var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "\"url('" + image[rand] + "')\""
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
}
else if (imageCount.length === image.length) {
imageCount = 0;
}
else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
Aucun commentaire:
Enregistrer un commentaire