Trying to make something simple in JS. Lets say I have two images, I want the page to load each image randomly. I want the two images to be swapped, when it gets clicked, it should change to the other image. How can I do this? Thanks
2 Answers 2
Here's plain javascript code (no frameworks used) that randomly loads one of the images in the imgs array as the initial image and then cycles through different images on each press of the button and a jsfiddle where you can see it work: http://jsfiddle.net/jfriend00/R7nUa/:
var imgs = [
"http://photos.smugmug.com/photos/344291068_HdnTo-Th.jpg",
"http://photos.smugmug.com/photos/344290962_h6JjS-Th.jpg",
"http://photos.smugmug.com/photos/344290515_bWVzK-Th.jpg"
];
// select a random image from the img URL array
function getRandomImage() {
var index = Math.floor(Math.random() * imgs.length);
return(imgs[index]);
}
// create image tag with random image
function initImage() {
var img = new Image();
img.id = "dynImage";
img.src = getRandomImage();
var o = document.getElementById("imageHolder");
o.appendChild(img);
}
// given the current URL, get the next URL in the array,
// wrapping back to beginning if needed
function nextImage(current) {
for (var i = 0; i < imgs.length; i++) {
if (imgs[i] == current) {
i++;
if (i >= imgs.length) {
i = 0;
}
return(i);
}
}
return(0);
}
// put a different image into the image tag
function swapImage() {
var o = document.getElementById("dynImage");
var next = nextImage(o.src);
o.src = imgs[next];
}
// initialize the button event handler
function initButton() {
var o = document.getElementById("swap");
if (o.addEventListener) {
o.addEventListener("click", swapImage);
} else {
o.attachEvent("onclick", swapImage);
}
}
initImage();
initButton();
You can put as many URLs into the imgs array as you want. You can see this working here: http://jsfiddle.net/jfriend00/R7nUa/ where I've also added preloading so the swap is instant when you press the button.
4 Comments
:sYou need this line somewhere in your script
var IMG1 = document.getElementById("IMG1");