Reputation: 77
I have an array of three images. I want to call the function from onClick
. Here's my code. I know can be done with jQuery but I'm just using plain JavaScript.
JavaScript
var myArray = ["_images/taste_logo_130w.gif","_images/logo.gif", "_images/winery_sign.jpg"];
var current = 0;
function imageTimer() {
if(current >= array.length) {
documnent.getElementById("logo").src = array[current];
current ++;
}
}
HTML
<img src="_images/logo.gif" id="logo" width="192" height="237" onClick=setInterval("imageTimer()", 3000); />
Upvotes: 0
Views: 72
Reputation: 56511
(1)
if(current >= array.length) { // fail always
since current is 0
and array.length is 3
So above condition will fail always.
(2) what happens on 4th click, there is no image. So better recycle it by resetting the value of current to zero.
Code:
var myArray = ["_images/taste_logo_130w.gif","_images/logo.gif", "_images/winery_sign.jpg"];
var current = 0;
function imageTimer() {
if(current <= array.length) {
documnent.getElementById("logo").src = array[current];
current ++;
}
else {
current = 0; //reset back to zero on 4th click
}
}
Upvotes: 1
Reputation: 825
You have an array myArray
but in the function you are calling the .lenght
on array
so change that to myArray.lenght
and you have array[current]
which should be myArray[current]
. Your if condition will also always be false if you have if(current >= myArray.lenght)
because (0 >= 3) is always false.
Try this:
var myArray = ["_images/taste_logo_130w.gif","_images/logo.gif", "_images/winery_sign.jpg"];
var current = 0;
function imageTimer() {
if(current < myArray.length) {
documnent.getElementById("logo").src = myArray[current];
current ++;
}
}
Upvotes: 0
Reputation: 2169
Perhaps so?
function imageTimer() {
if(current < array.length) {
current++;
}else{
current = 0;
}
documnent.getElementById("logo").src = array[current];
}
or shorter:
function imageTimer() {
(current < array.length) ? current++ : current = 0;
documnent.getElementById("logo").src = array[current];
}
Upvotes: 1
Reputation: 61
javascript:
var myArray = ["_images/
taste_logo_130w.gif","_images/logo.gif",
"_images/winery_sign.jpg"];
var current;
var timr;
function imageTimer() {
if(current < array.length) {
documnent.getElementById
("logo").src = array[current];
current ++;
}
else clearInterval(timr);
}
html:
<img src="_images/logo.gif" id="logo"
width="192" height="237" onClick="timr=setInterval
(function(){
current=0;
imageTimer();
}, 3000); "/>
Upvotes: -1