Vrutin
12-05-2012, 06:57 PM
Hey, I have just started scripting JavaScript and I got stuck when I wanted to change everytime the page is reloaded to have a new image.
Here is my current script:
var index = 1;
function randomContent() {
var mainContent = document.getElementById("mainContent");
var randomImg="images/content" + index++ + ".png";
mainContent.src=randomImg;
}
window.onload = function() {
// Load Random Images
randomContent();
}
It displays the first image. However, it doesn't change every-time to a new one.
DanInMa
12-05-2012, 08:31 PM
the index will always be the same unless you save information somehow between page views. you could use a cookie ( http://www.tutorialspoint.com/javascript/javascript_cookies.htm ) to record and use the information perhaps. This will work on a per user basis.
Old Pedant
12-05-2012, 08:45 PM
You could also simply choose a random index value. It is then *possible* that a user will get the same image 2 times in a row, but the odds of that will only be 1 in N, where N is how many available images you have.
It's not perfect, but it's simpler and may work well enough.
Vrutin
12-05-2012, 08:57 PM
You could also simply choose a random index value. It is then *possible* that a user will get the same image 2 times in a row, but the odds of that will only be 1 in N, where N is how many available images you have.
It's not perfect, but it's simpler and may work well enough.
Hey, I later on decided to do that ... its working as how I wanted, though I am getting some 0 when number is generated..
var index = Math.round(Math.random()*3);
if(index == 0)
{
index = Math.round(Math.random()*3);
}
function randomContent() {
var mainContent = document.getElementById("mainContent");
var randomImg="images/content" + index + ".png";
mainContent.src=randomImg;
}
window.onload = function() {
// Load Random Images
randomContent();
}
Go it working by changing to:
function randomContent() {
var index = Math.ceil(Math.random() * 3);
var mainContent = document.getElementById("mainContent");
var randomImg = "images/content" + index + ".png";
mainContent.src = randomImg;
}
Old Pedant
12-05-2012, 09:05 PM
VERY WRONG:
var index = Math.round(Math.random()*3);
if(index == 0)
{
index = Math.round(Math.random()*3);
}
RIGHT:
var numberOfImages = 3; // or however many you have
var index = 1 + Math.floor( Math.random() * numberOfImages );