I have a problem with a little javascript routine I am trying to write but after staring at it for hours, I can't get it to work, so its probably something trivial. I have a series of 11 images called dd0.jpg, dd1.jpg ....dd10.jpg and I'm trying to loop through them, and then when I get to dd10.jpg, the process reverses and then goes back to dd0.jpg
The javascript code is
<script>
var ddimagearray = [];
var ddn = 0;
var incrementing = true;
for(var i =0; i<11; i++)
{
ddimagearray[i] = new Image();
ddimagearray[i].src = "/dd/dd" + i + ".jpg";
}
var ddname = document.getElementById("ddimage");
var myVar = setInterval(function(){ changeimage() }, 100); // Milliseconds
function changeimage()
{
if (incrementing == true)
{
ddname.src = ddimagearray[ddn].src;
ddn++;
if(ddn == 14)
{
incrementing = false;
}
}
else
{
ddname.src = ddimagearray[ddn].src;
ddn--;
if(ddn == 0)
{
incrementing = true;
}
}
}
</script>
On a test page I have <center><img src="/dd/dd0.jpg" id="ddimage" class=ddimage/></center><script src="dd.js"></script>
Can anyone see anything desperately wrong?
You need to change 14
to 10
in incrementing == true
case, 14 will throw exception Uncaught TypeError: Cannot read property 'src' of undefined
because ddimagearray have only 10 items.
var ddimagearray = []; var ddn = 0; var incrementing = true; for(var i =0; i<11; i++) { ddimagearray[i] = new Image(); ddimagearray[i].src = "http://lorempixel.com/200/200/sports/" + i; } var ddname = document.getElementById("ddimage"); var myVar = setInterval(function(){ changeimage() }, 100); // Milliseconds function changeimage() { if (incrementing == true) { ddname.src = ddimagearray[ddn].src; ddn++; if(ddn == 10) { incrementing = false; } } else { ddname.src = ddimagearray[ddn].src; ddn--; if(ddn == 0) { incrementing = true; } } }
<img id="ddimage" src="http://lorempixel.com/200/200/sports/0/"/>
JSFiddle of your code works fine(except of-course for the limit of ddn as @jcubic posted).
Is this a simplified version of your actual code? Are you getting any errors?
your problem might be that ddimagearray
is not in scope of the changeImage
function so ddname.src = ddimagearray[ddn].src;
throws uncaught typeError
.
In your code is the line:
var myVar = setInterval(function(){ changeimage() }, 100); // Milliseconds
Replace it with the following and see what happens:
var myVar = setInterval("changeimage()", 100); // Milliseconds
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.