Rotating Images In Html
hello everyone i'm trying to get these images to rotate every 5 seconds in HTML, using javascript. I cant figure out why images are not rotating, if someone could assist me that wo
Solution 1:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var image1 = new Image()
image1.src = "dummyImg1.jpg"
var image2 = new Image()
image2.src = "dummyImg2.jpg"
var image3 = new Image()
image3.src = "dummyImg3.png"
</script>
</head>
<body>
<img src="dummyImg1.jpg" name="slide" >
<script type="text/javascript">
var step = 1
function slideit() {
document.images["slide"].src = eval("image" + step + ".src")
if (step < 3)
step++
else
step = 1
setTimeout("slideit()", 5000)
}
slideit()
</script>
</body>
</html>
Solution 2:
Your setTimeout function is incorrect, as you are passing it a string, not a function, and you don't close your function. It is also very inefficient to create a new image item every time; an array will suit you much better. Finally, I think you want to use setInterval not setTimeout.
A working example is here: http://jsfiddle.net/HUP5W/2
Obviously, the images don't work, but, if you look at the console, it is working correctly.
var image = document.getElementById("img1");
var src = ["concert2.gif","concert3.gif","concert4.gif","concert5.gif","concert1.gif"];
var step=0
function slideit() {
image.src = src[step];
image.alt = src[step];
if(step<4) {
step++;
} else {
step=0;
}
}
setInterval(slideit,5000);
Post a Comment for "Rotating Images In Html"