Reputation: 5667
As you can see, I have three arrays which store three separate images each. Currently, you can cycle through each array by mouse-clicking the image to get a new image each time. What I want to do is incorporate the "Random!" button below to ask each array to change to a random image from within their respective array, and to do this simultaneously. So say you click "Random!" and then each array will pick a random image from within itself and display it.
I'm not sure how to even go about doing this. Any thoughts?
<script type="text/javascript">
imgs=Array("pic1.jpg","pic2.jpg","pic3.jpg");
var x=0;
function change() {
document.getElementById("img").src=imgs[++x];
if (x==2) {
x=-1;
}
}
if (!imgs[x+1]) {
x=-1;
}
</script>
<img src="pic1.jpg" id="img" onmousedown="change()" style="cursor: pointer;">
<img src="" id="img" alt="" onmousedown="change()"><br>
<!-- /slider -->
<script type="text/javascript">
imgs1=Array("pic4.jpg","pic5.jpg","pic6.jpg");
var x1=0;
function change1() {
document.getElementById("img1").src=imgs1[++x1];
if (x1==2) {
x1=-1;
}
}
if (!imgs1[x1+1]) {
x1=-1;
}
</script>
<img src="pic4.jpg" id="img1" onmousedown="change1()" style="cursor: pointer;">
<img src="" id="img1" alt="" onmousedown="change1()"><br>
<!-- /slider1 -->
<script type="text/javascript">
imgs2=Array("pic7.jpg","pic8.jpg","pic9.jpg");
var x2=0;
function change2() {
document.getElementById("img2").src=imgs2[++x2];
if (x2==2) {
x2=-1;
}
}
if (!imgs2[x2+1]) {
x2=-1;
}
</script>
<img src="pic7.jpg" id="img2" onmousedown="change2()" style="cursor: pointer;">
<img src="" id="img2" alt="" onmousedown="change2()"><br>
<!-- /slider2 -->
<a href="#" data-role="button">Random!</a>
Upvotes: 0
Views: 400
Reputation: 956
You can use a randomiser function to pick a random array index:
function getRandomIndex(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
So in your change functions you can then do:
document.getElementById("img1").src=imgs1[getRandomIndex(0,imgs1.length - 1)];
Upvotes: 1