Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple image rotation out of my brain 2

Status
Not open for further replies.

Sleidia

Technical User
May 4, 2001
1,284
FR
Sorry, my Javascript skills have become too rusty :( ...
... can someone be kind enough to remind me how to cycle endlessly through an array of images every n seconds so that a div background changes every 5 seconds?

I'm stuck here :

Code:
var pics = new Array('pic_1.png', 'pic_2.png');

for (var i = 0; i < pics.length; i++) {

document.getElementById('my_pics').style.backgroundImage = 'url(my_dir/'+ pics[i] +')';

}

Thanks A LOT :)
 
Something like this. (maybe use type rather than language to suit taste.)
[tt]
<script language="javascript">
var pics = new Array('pic_1.png', 'pic_2.png');
var idx=0; //intialized to some picture
function doit() {
document.getElementById('my_pics').style.backgroundImage='url('+pics[idx]+')';
idx=(idx+1) % pics.length;
setTimeout(doit,1000);
}
//trigger it via window onload or some other means
window.onload=doit;
</script>
[/tt]
 
>changes every 5 seconds
I should incorporate this need.
[tt] setTimeout(doit,[red]5[/red]000);[/tt]
 
Thanks a lot Tsuji :)
Makes much more sense!

BTW, I've always wondered: are you Japanese?
 
Thanks! I am just a friend of the globe and my admiration of Japanese culture and people go with it.
 
Thanks for this precious piece of information :)
Watashimo nihon no koto wo yoku shitteru yo ;)
 
Sleida, one thing that I do when I know I want something to loop infinitely is to use setInterval instead of setTimeout. This way I don't have to re-initiate the timeout function on every pass of the function. You just initiate the interval once and let javascript do the rest:

Using tsuji's code:
Code:
function doit() {
   document.getElementById('my_pics').style.backgroundImage='url('+pics[idx]+')';
   idx=(idx+1) % pics.length;
}
//trigger it via window onload or some other means
window.onload = function () {
   [!]setInterval(doit, 1000);[/!]
};

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Thanks a lot Kaht :)
I like that idea!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top