Reputation:
in folder i have following images w1.jpg,w2.jpg...... w7.jpg, now i have this code for display w1.jpg on my html page
<html>
<body >
<div style='position:absolute;z-index:0;left:0;top:0;width:100%;height:100%'>
<img src='w1.jpg' style='width:99%;height:99%' alt='[]' />
</div>
</body>
</html>
and i want to know,how to write script,which changes images from w1.jpg to w7.jpg in a specific interval,as i know for this there is used setInterval function in javascript,but could you help to understand how i have to use it in my code?thanks very much
Upvotes: 0
Views: 13327
Reputation: 3381
Well without getting into the details of how you could improve the code (avoid inline css, etc) the simplest way woud be to give the image an id, then put this this at the end of your HTML page
<div style='position:absolute;z-index:0;left:0;top:0;width:100%;height:100%'>
<img id="change-me" src='w1.jpg' style='width:99%;height:99%' alt='[]' />
</div>
<script>
var
images = [ "w1.jpg", "w2.jpg", "w3.jpg" ] //the list of images
, imgToCHange = document.getElementById( 'change-me' )
, interval = 1000 //in ms
;
setInterval( function(){
images.unshift( images.pop() );
imgToCHange.src = images[0];
}, interval );
</script>
</body>
</html>
Upvotes: 0
Reputation: 4539
You have compulsory define image id
var i=2;
function change_image()
{
if(i==8)
{
i=1;
}
var img="w"+i+'.jpg'
document.getElementById("img1").src=img;
i++;
setTimeout("change_image()",5000);
}
HTML Code
<img id="img1" src="w1.png" />
Call javascript function it will change image in 5 seconds
<script>
change_image();
</script>
Upvotes: 1
Reputation: 12322
I think you should background-image style for this. This is much better way than creating z-indexed div on the background.
Then change CSS by javascript (supposing you use jQuery for selecting body element):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var ii = 1;
setInterval(function(){
var image = "w" + ii + ".jpg";
console.log(image);
$("body").css("background-image", "url('" + image + "')");
ii++;
}, 1000);
</script>
Of course, you need to stop at the right time, when the last image comes.
Edit from comment below: If you don't want to use jQuery (however I encourage you to get familiar with it), you can change the line starting with $
symbol to:
document.body.style.backgroundImage = "url('" + image + "')";
Upvotes: 1