• Need a setTimeout related thingy
    7 replies, posted
I need a function which changes images from 10 to 10 seconds, and needs to be used with setTimeout. If anyone could tell me how I'd be deeply grateful.
More information would be awesome?
[code] var imgs = ["img1.jpg", "img2.jpg"]; // and so on... var i = 0; function changeit() { document.getElementById("yourImg").setAttribute("src", imgs[++i]); if(i+1 == imgs.length) i = 0; setTimeout(changeit, 10000); } window.onload = function() { setTimeout(changeit, 10000); } [/code] Not tested, should do the trick
[QUOTE=turby;18757800][code] [code]var imgs = ["img1.jpg", "img2.jpg"]; // and so on... var i = 0; function changeit() { document.getElementById("yourImg").setAttribute("src", imgs[++i]); if(i+1 == imgs.length) i = 0; setTimeout(changeit, 10000); } window.onload = function() { setTimeout(changeit, 10000); } [/code] Not tested, should do the trick[/QUOTE] The first picture appears but it doesn't change, I have 2 pics so far, which are named sporting and radio, can you tell me if there's anything wrong: var imgs = ["sporting.png", "radio.jpg"]; // and so on... var i = 0; function changeit() { document.getElementById("sporting.png").setAttribute("src", imgs[++i]); if(i+1 == imgs.length) i = 0; setTimeout(changeit, 10000); } window.onload = function() { setTimeout(changeit, 10000); } And by the way, all of this is placed in an external JavaScript file.
This is part of a coursework which I have to deliver tomorrow, and I really need to have this done, can I get a fast response? Thanks.
document.getElementById("sporting.png").setAttribu te("src", imgs[++i]); That's probably wrong. You need to add an image with a unique ID: <img src="sporting.png" id="thisismyimage" alt="" /> And then use that in the code: document.getElementById("thisismyimage").setAttribute("src", imgs[++i]);
It's working now, but it changes to the second picture in less than a second and after the second picture it doesn't go back to the first one, I need it to that, like a loop. [quote] var imgs = ["sporting.png", "scp.jpg"]; // and so on... var i = 0; function changeit() { document.getElementById("thisismyimage").setAttribute("src", imgs[++i]); if(i+1 == imgs.length) i = 0; setTimeout(changeit, 10000); } window.onload = function() { setTimeout(changeit, 10000); } [/quote] And in the html file I inserted this in the div where I want the images in: [quote] <img src="imagens/sporting.png" id="thisismyimage" alt="" /> [/quote]
Ohh, it's homework? Do it yourself, lest you not learn
Sorry, you need to Log In to post a reply to this thread.